每当用户按下返回按钮同时使用 AsyncTask 从 Web 获取 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 而其他活动排在首位。