你在onRetainNonConfigurationInstance()
上傳什麼?我所做的是傳遞一個包含AsyncTask
的對象,然後嘗試檢索getLastNonConfigurationInstance()
中的值。
編輯:第二個想法,這將取決於你想要做什麼後,配置更改。如果要終止AsyncTask
,然後請撥打cancel()
就可以了。如果你想在方向改變後繼續處理,那麼你必須堅持這個任務。
你可以通過在AsyncTask
這樣節省了Activity
:
private MyAsyncTask searchTask;
@Override
public void onCreate(Bundle savedInstance){
super.onCreate(savedInstance);
if (getLastNonConfigurationInstance()!=null) {
SavedObject savedObj = (SavedObject)getLastNonConfigurationInstance();
searchTask = savedObj.getAsyncTask();
searchTask.attach(this);
} else {
searchTask = new MyAsyncTask(this);
searchTask.execute();
}
}
@Override
public Object onRetainNonConfigurationInstance(){
searchTask.detach();
final SavedObject savedObj = new SavedObject();
savedObj.setAsyncTask(searchTask);
return savedObj;
}
private class MyAsyncTask extends AsyncTask<Void, Void, Void> {
MyActivity parentActivity = null;
MyAsyncTask (MyActivity activity) {
attach(activity);
}
void attach(MyActivity activity) {
this.parentActivity=activity;
}
void detach() {
parentActivity=null;
}
// Do your thread processing here
}
private class SavedObject {
private MyAsyncTask asyncTask;
public void setAsyncTask(MyAsyncTask asyncTask){
this.asyncTask = asyncTask;
}
public MyAsyncTask getAsyncTask() {
return asyncTask;
}
}