2013-01-16 76 views
1

好吧,我有一個程序,需要等到android完全啓用WiFi適配器。我有這個活動代碼,它的工作原理,但老實說,我不認爲這是等待一些任務完成(在這種情況下,Android需要啓用無線)的正確方式。顯示進度對話框,直到任務完成其工作

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. 如果無線網絡被禁用,直到任務完成(在這種情況下,無線網絡能夠完全地)執行if語句(顯示進度對話框,並啓用WiFi)
  2. 顯示進度對話框
  3. 當無線網絡連接啓用停止顯示進度對話框

在此先感謝!

+0

使用的AsyncTask或處理程序 – njzk2

回答

0

使用的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(); 
} 
} 
0

像這樣將工作:

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); 
    } 
}