ilo*_*mbo 5 lifecycle android android-asynctask
我已经测试了AsyncTasks没有被破坏以及它们的启动活动的声明.这是事实.
我让AsyncTask Log.i()每3秒发布一条消息,持续1分钟.我在活动Log.i()的onDestroy()方法中加入了麻烦.
我看到活动被破坏了,但是AsyncTask一直运行直到它完成所有20条Log.i()消息.
我很困惑.
如果AsyncTask publishProgress()进入被破坏的用户界面怎么办?
我想会发生某种异常,对吧?
如果AsyncTask将数据存储在全局变量中,该class Application怎么办?
不知道在这里,NullPointer例外吗?
如果应用程序重新启动怎么办?
它可能会推出一个新的AsyncTask.它可以重新连接仍在运行的AsyncTask吗?
母应用程序被销毁后,AsyncTask是不朽的吗?
也许是的,当UI应用程序不再可见时,所有LogCat应用程序如何记录日志消息,可能会被破坏?当你重新打开它们时,它们会向你显示在它"死亡"时产生的消息.
所有这些似乎都是一个讨论,但问题在于标题.我有这个孤立的AsyncTask,我非常想重新连接应用程序重新启动,但我不知道该怎么做.
我忘了告诉为什么这很重要.当方向发生变化时,应用程序会被销毁.而且我不想丢失AsyncTask生成的数据,我不想阻止它并重新启动它.我只是希望它继续进行并在方向更改完成后重新连接.
我希望我已经得到了这个权利,因为它来自我不再使用的一些旧代码(我现在使用 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
}
}
Run Code Online (Sandbox Code Playgroud)
关键是要使用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);
}
Run Code Online (Sandbox Code Playgroud)
然后我有一个调用的方法,如果指示为真,则doDownload()调用该方法。是在的方法中设置的。onResume()BooleandownloadCompleteBooleanonPostExecute(...)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);
}
}
Run Code Online (Sandbox Code Playgroud)