我在我的活動中調用一個函數,這基本上是一個異步任務,通過webservice從遠程服務器獲取數據。如何取消異步任務
private void myAsyncTask() {
new AsyncTask<Object, Object, Object>() {
@Override
protected void onPreExecute() {
progress_Dialog = ProgressDialog.show(a, "", "Loading");
}
@Override
protected Integer doInBackground(Object... params) {
try
{
try {
MenuService menuService = new MenuServiceImpl();
MenuServiceResponse partnerMenu;
partnerMenu = menuService.getMenu();
productlist=Menu.getMenu().getMenuEntries();
System.gc();
return 0;
} catch (myServiceException e) {
bgFlag=true;
e.printStackTrace();
}
}
catch (Exception e) {
bgFlagForserviceExeption=true;
e.printStackTrace();
}
} return 0;
}
@Override
protected void onPostExecute(Object result) {
if (progress_Dialog != null) {
progress_Dialog.dismiss();
}
try
{
if(bgFlagForserviceExeption)
{
MyAlertDialog.ShowAlertDialog(ShopActivity.this, "", "Please try again later", "OK");
}
if(bgFlag==false)
{
adapter = new ShopAdapter(
ShopActivity.this, productlist);
allproduts.setAdapter(adapter);
}
else
{
MyAlertDialog.ShowAlertDialog(ShopActivity.this, "", " Please try again later", "OK");
}
}
catch(Exception e)
{
adapter=null;
}
}
}.execute();
}
當我把這個活動的進度條會顯示,直到doinbackground()ends.How我可以從手機按後退按鈕後臺進程退出,現在的問題是,我將不得不等待,直到即使我按下後退按鈕,後臺進程也會完成。如何才能達到此效果
你不能用'doInBackground'做到這一點是這樣的...'AsyncTask.cancel'只能幫助,那麼你在'doInBackground'循環,在你每一次迭代做的事情檢查isCancelled(),然後打破循環... – Selvin
更多的explenation(關於爲什麼'AsyncTask.cancel'不適用於此)...實際上有一個很大的機會,你的代碼「卡住」在' getMenu()'或'getMenuEntries()'方法和'doInBackground'你沒有可能停止他們的... – Selvin
http://stackoverflow.com/questions/6356956/onbackpressed-doesnt-trigger-when-showing-progressdialog – Selvin