我已经测试了AsyncTasks不会与其启动活动一起销毁的语句。这是真的。
我让 AsyncTask 每 3 秒发布一条 Log.i()
消息,持续 1 分钟。我把Log.i()
消息放在活动的onDestroy()
方法中。
我看到活动被销毁,但 AsyncTask 继续运行,直到它完成所有 20 条Log.i()
消息。
我很困惑。
-
如果 AsyncTask
publishProgress()
到被破坏的 UI 中怎么办?
我想会发生某种异常,对吧? -
如果 AsyncTask 将数据存储在全局变量
class Application
中怎么办?
不知道这里,空指针异常? -
如果应用程序重新启动怎么办?
它可能会启动一个新的AsyncTask。它可以与仍在运行的 AsyncTask 重新连接吗? -
母应用被毁后,AsyncTask是不朽的吗?
也许是的,当 UI 应用程序不再可见(也许被破坏(时,所有 LogCat 应用程序如何继续记录消息?当您重新打开它们时,它们会向您显示"死亡"时生成的消息。
这一切似乎都是一个讨论,但问题在标题中。我有这个孤儿AsyncTask,我非常想在应用程序重新启动时重新连接到它,但我不知道该怎么做。
我忘了告诉为什么这非常重要。当方向发生更改时,应用程序将被销毁。而且我不想丢失AsyncTask产生的数据,我不想停止它并重新启动它。我只是希望它继续前进并在方向更改完成后重新连接。
我希望我做对了,因为它来自我不再使用的一些旧代码(我现在使用IntentService
来做以前做的事情(。
这是我在主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()
的方法,如果指示 downloadComplete
Boolean
为真,则从 onResume()
调用该方法。Boolean
设置在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);
}
}