好的我有一个程序需要等到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();
}
}
有人可以告诉我,在某项任务完成之前,等待程序执行的正确方法是什么?所以计划方案:
提前致谢!
答案 0 :(得分:1)
Subclass AsyncTask,这正是为AsyncTask创建的那种东西。
http://developer.android.com/reference/android/os/AsyncTask.html
答案 1 :(得分: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();
}
}
答案 2 :(得分: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);
}
}
答案 3 :(得分:0)
为此使用AsyncTask。在OnPreExecute()中显示您的进度条,并在doInBackground()中执行加载过程或需要时间的事情,最后在onPostExecute()中关闭进度对话框。 这是工作样本 -
http://huuah.com/android-progress-bar-and-thread-updating/
希望它能帮到你