我希望我有这个权利,因为它来自我不再使用的一些旧代码(我现在使用IntentService来做以往的事情).
这是我在主Activity中下载文件时最初的内容…
public class MyMainActivity extends Activity {
FileDownloader fdl = null;
...
// This is an inner class of my main Activity
private class FileDownloader extends AsyncTask {
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()的方法,如果指示downloadComplete的布尔值为true,则从onResume()调用该方法.布尔值在FileDownloader的onPostExecute(…)方法中设置.
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);
}
}
这篇博客讨论了如何在Android应用中从主Activity下载文件时,从使用AsyncTask转向IntentService。作者指出,IntentService更适合处理长时间运行的任务,因为它在后台线程中运行,避免了配置更改时需要手动保留任务状态的问题。文章详细介绍了如何利用onRetainNonConfigurationInstance()方法保存AsyncTask实例,并在设备旋转等配置改变后重新恢复下载过程。在doDownload()方法中,作者展示了如何检查是否已保留下载任务实例,若未保留则创建新的FileDownloader实例并开始下载。
804

被折叠的 条评论
为什么被折叠?



