每当用户按下后退按钮使用AsyncTask从网络获取xml数据时,我的应用程序将强制关闭状态。我怎么能解决这个问题。提前致谢。
public class InboxActivity extends Activity {
public static ExpandableListView mailList;
List<HashMap<String,String>> list;
MailList asyncTaskMailList;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.inbox_layout);
ConstantValues.footerCurrentActivity=InboxActivity.this;
mailList=(ExpandableListView)findViewById(R.id.expandableListView1);
HomePageActivity.homePageTabHost.getTabWidget().getChildTabViewAt(ConstantValues.CURRENT_POSITION)
.setBackgroundDrawable(getResources().getDrawable(R.drawable.tab_widget_normal));
asyncTaskMailList=new MailList();
asyncTaskMailList.execute();
}
private OnChildClickListener childClickListener=new ExpandableListView.OnChildClickListener() {
public boolean onChildClick(ExpandableListView parent, View v,int groupPosition, int childPosition, long id) {
ConstantValues.STATION_NAME=ConstantValues.inboxStations.get(groupPosition);
ConstantValues.CURRENT_POSITION=1;
startActivity(new Intent(InboxActivity.this, HomePageActivity.class));
return false;
}
};
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_BACK){
this.getParent().onBackPressed();
asyncTaskMailList.cancel(true);
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
protected void onStop() {
super.onStop();
asyncTaskMailList.cancel(true);
}
@Override
protected void onDestroy() {
asyncTaskMailList.cancel(true);
super.onDestroy();
}
class MailList extends AsyncTask<String, String, String>
{
@Override
protected void onPreExecute() {
super.onPreExecute();
NetworkExceptionPopUp.showProgressBar();
}
@Override
protected String doInBackground(String... params) {
list=new ArrayList<HashMap<String,String>>();
WebServerCall.getInboxMail(InboxActivity.this);
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
mailList.setAdapter(new InboxAdapter(InboxActivity.this));
NetworkExceptionPopUp.dismissProgressBar();
mailList.setOnGroupClickListener(null);
mailList.setOnChildClickListener(childClickListener);
mailList.setClickable(true);
}
}
} 上面的代码是我更新的代码。这也有时显示异常。在这里,我使用onStop()和OnDestroy()来取消AsyncTask,而其他活动则排在首位。
答案 0 :(得分:2)
@Override
protected void onPreExecute() {
super.onPreExecute();
NetworkExceptionPopUp.showProgressBar();
/** add this line to your progressDialog so that diaolg as well your background operation wont stop in intermediate state. */
// pd.setCancelable(false);
}
所以现在当你点击后退按钮时,Dialog不会被解雇。
希望对你有所帮助。
答案 1 :(得分:1)
private MailList task;
@Override
public void onCreate(Bundle savedInstanceState) {
...
task = new MailList().execute();
...
}
@Override
public void onBackPressed() {
if (task != null && task.getStatus() == AsyncTask.Status.RUNNING) {
task.cancel(true);
}
...
}
...