0

當活動終止時,例如屏幕方向更改後,是否可以更改AsyncTask活動上下文?否則它會產生一個錯誤,因爲當活動結束時AsyncTask的活動環境也消失了。Android AsyncTask上下文終止

我做功課如下:

public void onSaveInstanceState(Bundle savedInstanceState) <- doesn't solve 
public Object onRetainNonConfigurationInstance() <- doesn't solve 
android:configChanges="keyboardHidden|orientation" 
        <- solved but doesn't handle well relative layouts 

回答

0

你在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; 
} 
} 
0
在非同步任務的OnCancel方法

把完成();

 public void onCancel(DialogInterface dialog) { 
     cancel(true); 
     dialog.dismiss(); 
     finish(); 
    }