我坐在一個代碼上的5小時,其中AyncTask
運行不正常。我剛剛創建了另一個簡單的Activity
(因爲在最後一個onPostExecute()
不起作用),現在這個簡單的Activity
也不會啓動AsyncTask
。任何人都可以看到我做錯了什麼?AsyncTask甚至沒有啓動
public class ServerStatus extends Activity {
Context context;
private ProgressDialog pd;
int a;
TextView test;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.server_status);
context=this;
test=(TextView) findViewById(R.id.welcomemessage);
new Download().execute();
}
public class Download extends AsyncTask<Void, Void, Void>{
protected Void onPreExecute(Void... arg0) {
pd = new ProgressDialog(context);
pd.setTitle("Processing...");
pd.setMessage("Please wait.");
pd.setCancelable(false);
pd.setIndeterminate(true);
pd.show();
return null;
}
@Override
protected Void doInBackground(Void... arg0) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
a++;
return null;
}
protected Void onPostExecute(Void... arg0) {
if (pd!=null)
pd.dismiss();
test.setText(a);
return null;
}
}
}
另外,是否NavigationDrawer
阻止UI線程?因爲我實施它時甚至不能更新TextView
。
您應該在onProgressUpdate()內做UI組件修改。導航抽屜不會阻塞UI線程。當你嘗試並運行它時會發生什麼? – 2014-09-30 20:10:09
這裏是我的[回答類似的問題] [1] [1]:http://stackoverflow.com/questions/25752210/cant-see-progressdialog-while-asynctask-run-in-background/25752553#25752553 – user3144836 2014-09-30 20:14:37
那麼,我是從onPostExecute()更新UI線程,所以也許有我的問題(它沒有更新任何東西,甚至沒有做任何事情,就像它沒有被調用)。那麼明天再試試看吧。感謝您的建議。 – Darknez 2014-09-30 20:15:03