gpt4 book ai didi

android - 即使应用程序被销毁,AsyncTask 也将始终运行?

转载 作者:IT老高 更新时间:2023-10-28 23:20:16 26 4
gpt4 key购买 nike

我有一个应用程序,因为你不能在我使用 AsyncTask 的主线程上进行网络操作,所以问题是一旦我 execute() AsyncTask 然后我 finish() Activity ,也许用户会 finish() 整个应用程序,所以我是想知道的是:

  1. AsyncTask 是否会始终完成 doInBackground()onPostExecute(),即使应用程序已关闭,只要 execute() 在应用运行时被调用?

最佳答案

您将能够对此进行测试。是的,确实如此。如果调用了执行,您可以看到 Asynctask 仍将执行,除非它对前台或 UI 相关的操作。 (可能会导致启动器崩溃)。


但是,如果它靠近系统。它可能会或可能不会继续执行该方法。我已经测试并回答了here .回复评论:已测试:

@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 &#39;android&#39; 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">
//....

关于android - 即使应用程序被销毁,AsyncTask 也将始终运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16204693/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com