JRo*_*wan 17 android android-lifecycle android-asynctask
我有一个应用程序,因为你不能做我使用的主线程上的网络操作AsyncTask,所以问题是,一旦我execute()的AsyncTask右后,我finish()的活动,也许用户将finish()整个应用程序,所以我"我想知道的是:
AsyncTask永远结束doInBackground()和onPostExecute()即使该应用程序是只要关闭execute()了该应用程序正在运行的时候叫什么?wts*_*g02 14
你将能够测试这个.是的确如此.如果调用了execute,你可以看到Asynctask仍会执行,除非它对forground或UI做了些什么.(它可能导致发射器崩溃).
但是,如果它靠近系统.它可能会也可能不会继续执行该方法.我已经测试并回答了这里.回复评论:经过测试:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Worker().execute();
}
private class Worker extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... arg0) {
Log.i("SomeTag",
"start do in background at " + System.currentTimeMillis());
String data = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(
"https://stackoverflow.com/questions/tagged/android");
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
data = EntityUtils.toString(httpEntity);
Log.i("SomeTag",
"doInBackGround done at " + System.currentTimeMillis());
} catch (Exception e) {
}
return data;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.i("SomeTag", System.currentTimeMillis() / 1000L
+ " post execute \n" + result);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.i("SomeTag", System.currentTimeMillis() / 1000L + " onDestory()");
}
04-24 21:42:57.981: I/SomeTag(5961): start do in background at 1366854177994
04-24 21:43:00.974: I/SomeTag(5961): 1366854180 onDestory()
04-24 21:43:02.946: I/SomeTag(5961): doInBackGround done at 1366854182946
04-24 21:43:02.946: I/SomeTag(5961): 1366854182 post execute
04-24 21:43:02.946: I/SomeTag(5961): <!DOCTYPE html>
04-24 21:43:02.946: I/SomeTag(5961): <html>
04-24 21:43:02.946: I/SomeTag(5961): <head>
04-24 21:43:02.946: I/SomeTag(5961):
04-24 21:43:02.946: I/SomeTag(5961): <title>Newest 'android' Questions - Stack Overflow</title>
04-24 21:43:02.946: I/SomeTag(5961): <link rel="shortcut icon" href="http://cdn.sstatic.net/stackoverflow/img/favicon.ico">
//....
Run Code Online (Sandbox Code Playgroud)
onPostExecute()从UI线程调用 - 因此如果UI线程不再运行,它将不会继续运行.但是doInBackGround()从一个单独的工作线程运行,所以它将一直持续到完成(或者如果JVM进程被操作系统杀死,这也是可能的).请注意,AsyncTasks仅建议用于较短的UI绑定后台任务,而不是长时间运行的后台工作(几秒钟).
简而言之,你不能假设它会继续下去,绝对不会假设它会发布它的进度或调用onPostExecute().
当您在Activity上调用finish()时,Activity被破坏,但主线程未被破坏。[注意:活动在主线程上运行。活动不是主线程。]
因此,将执行后台线程上的doInBackground()和主线程上的onPostExecute()。但是,如果onPostExecute()执行任何与UI相关的任务,则将获得ANR,因为此时没有UI。例如,如果仅在onPostExecute()中打印Log.d()语句,则该语句将在Logcat中可见。
**仅当进程处于活动状态且未被Android Low Memory Killer杀死时,才有可能。
| 归档时间: |
|
| 查看次数: |
21298 次 |
| 最近记录: |