Android Asynctask Context Terminated
When an Activity terminates, e.g. after screen orientation changing, is that possible to change an AsyncTask activity context? Else it will create an error because when the activit
Solution 1:
What do you pass on your onRetainNonConfigurationInstance()
? What I do is pass an object to it containing the AsyncTask
, and then I try to retrieve the value in getLastNonConfigurationInstance()
.
EDIT: On second thought, it would depend on what you want to do after a configuration change. If you want to terminate the AsyncTask
, and then call cancel()
on it. If you want to continue its processing even after an orientation change, then you have to hold on to the task.
You can do that by saving the Activity
in the AsyncTask
like this:
privateMyAsyncTask searchTask;
@OverridepublicvoidonCreate(Bundle savedInstance){
super.onCreate(savedInstance);
if (getLastNonConfigurationInstance()!=null) {
SavedObject savedObj = (SavedObject)getLastNonConfigurationInstance();
searchTask = savedObj.getAsyncTask();
searchTask.attach(this);
} else {
searchTask = newMyAsyncTask(this);
searchTask.execute();
}
}
@OverridepublicObjectonRetainNonConfigurationInstance(){
searchTask.detach();
final SavedObject savedObj = newSavedObject();
savedObj.setAsyncTask(searchTask);
return savedObj;
}
privateclassMyAsyncTaskextendsAsyncTask<Void, Void, Void> {
MyActivity parentActivity = null;
MyAsyncTask (MyActivity activity) {
attach(activity);
}
voidattach(MyActivity activity) {
this.parentActivity=activity;
}
voiddetach() {
parentActivity=null;
}
// Do your thread processing here
}
privateclassSavedObject {
privateMyAsyncTask asyncTask;
publicvoidsetAsyncTask(MyAsyncTask asyncTask){
this.asyncTask = asyncTask;
}
publicMyAsyncTaskgetAsyncTask() {
return asyncTask;
}
}
Solution 2:
in the OnCancel method of your asynch task put finish();
public void onCancel(DialogInterface dialog) {
cancel(true);
dialog.dismiss();
finish();
}
Post a Comment for "Android Asynctask Context Terminated"