1

好的,我有一个程序需要等到 android 完全启用 wifi 适配器。我有这个活动代码并且它可以工作,但老实说,我认为这不是等待某些任务完成的正确方法(在这种情况下,android 需要启用 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();
    }
}

有人可以告诉我,等待程序执行直到某个任务完成的正确方法是什么?所以程序场景:

  1. 如果 wifi 被禁用,执行 if 语句(显示进度对话框并启用 wifi)
  2. 显示进度对话框,直到任务完成(在这种情况下 wifi 完全启用)
  3. 启用 wifi 时停止显示进度对话框

提前致谢!

4

4 回答 4

1

子类 AsyncTask,这正是 AsyncTask 的创建目的。

http://developer.android.com/reference/android/os/AsyncTask.html

于 2013-01-16T12:24:44.327 回答
0

Using AsyncTask:

private class MyTask extends AsyncTask<URL, Integer, Long> {

   private Context context;

   public MyTask(Context context) {
     this.context = context;
   }

   protected void onPreExecute() {
      progressDialog = ProgressDialog.show(context, "", "msg", true); 
   }

  protected Long doInBackground(URL... urls) {
       //do something
  }

 protected void onPostExecute(Long result) {
     progressDialog.dismiss();  
 }
}
于 2013-01-16T12:25:39.313 回答
0

Something like this will work:

    if(!wm.isWifiEnabled()) {

        pd = ProgressDialog.show(this, "Stand by", "Doing work");
        WifiManager wifiManager = (WifiManager)getBaseContext().getSystemService(Context.WIFI_SERVICE);
        wifiManager.setWifiEnabled(true);

    }

public void testWifi(){


  WifiManager wifi = (WifiManager)getSystemService(Context.WIFI_SERVICE);
  if (wifi.isWifiEnabled()){
    pd.dismiss();
    //continue code
  }else{
    new Handler().postDelayed(new Runnable() {
      testWifi();
    } , 200);
  }
}
于 2013-01-16T12:27:58.257 回答
0

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

于 2013-01-16T12:58:02.957 回答