Ok i have a program which needs to wait until android enables wifi adapter completely. I have this activity code and it works, but honestly i don’t think that this is proper way of waiting to some task to be finished ( in this case , android needs to enable wifi ).
public class MainActivity extends Activity implements Runnable {
ProgressDialog pd;
WifiManager wm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
wm = (WifiManager) getSystemService(WIFI_SERVICE);
if(!wm.isWifiEnabled()) {
pd = ProgressDialog.show(this, "Stand by", "Doing work");
Thread t = new Thread(this);
t.start();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
@Override
public void run() {
wm.setWifiEnabled(true);
while(wm.getWifiState() != 3) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
pd.dismiss();
}
}
Can someone please tell me, how is the proper way of waiting a program from executing until some task is finished? So program scenario:
- If wifi is disabled, execute if statement ( show progress dialog and enable wifi )
- Show progress dialog until task is done ( in this case wifi enables completely)
- When wifi is enabled stop showing progress dialog
Thanks in advance!
Use AsyncTask for this. Show your progress bar in OnPreExecute() and do the loading process or something that needs time in doInBackground() and finally dismiss your progress dialog in onPostExecute().
Here is the working sample-
http://huuah.com/android-progress-bar-and-thread-updating/
Hope it will help you