我希望我做对了,因为它来自一些我不再使用的旧代码(我现在使用 anIntentService
来做这曾经做的事情)。
这是我最初在我的主目录中下载文件时所拥有的Activity
...
public class MyMainActivity extends Activity {
FileDownloader fdl = null;
...
// This is an inner class of my main Activity
private class FileDownloader extends AsyncTask<String, String, Boolean> {
private MyMainActivity parentActivity = null;
protected void setParentActivity(MyMainActivity parentActivity) {
this.parentActivity = parentActivity;
}
public FileDownloader(MyMainActivity parentActivity) {
this.parentActivity = parentActivity;
}
// Rest of normal AsyncTask methods here
}
}
关键是用来onRetainNonConfigurationInstance()
“保存” AsyncTask
.
Override
public Object onRetainNonConfigurationInstance() {
// If it exists then we MUST set the parent Activity to null
// before returning it as once the orientation re-creates the
// Activity, the original Context will be invalid
if (fdl != null)
fdl.setParentActivity(null);
return(fdl);
}
然后我有一个调用的方法doDownload()
,onResume()
如果Boolean
指示downloadComplete
为真,则调用该方法。Boolean
是在 的方法onPostExecute(...)
中设置的FileDownloader
。
private void doDownload() {
// Retrieve the FileDownloader instance if previousy retained
fdl = (FileDownloader)getLastNonConfigurationInstance();
// If it's not null, set the Context to use for progress updates and
// to manipulate any UI elements in onPostExecute(...)
if (fdl != null)
fdl.setParentActivity(this);
else {
// If we got here fdl is null so an instance hasn't been retained
String[] downloadFileList = this.getResources().getStringArray(R.array.full_download_file_list);
fdl = new FileDownloader(this);
fdl.execute(downloadFileList);
}
}