在的onDestroy AsyncTask.execute的影响 [英] implications of AsyncTask.execute in onDestroy
问题描述
我在的onDestroy
函数这个code运行:
I have this code running in my onDestroy
function:
@Override
protected void onDestroy() {
if (!(null == theUser.glideId)) {
JSONObject req = new JSONObject();
try {
req.put("actionKey", "UserPresenceInactive");
req.put("userId", theUser.userId);
new ServerRequest().execute(req); //Run an AsyncTask
} catch (JSONException e) {
e.printStackTrace();
}
}
super.onDestroy();
}
在的AsyncTask
我发送一个请求到服务器(即回来只是一个200响应)。
In the AsyncTask
I send a request to a server (that comes back with just a 200 response).
我的问题是,会有什么影响(如果有的话),这样做的?
My question is, what are the implications (if any) for doing this?
活动是否被摧毁?该应用是否保持清醒,可能会进入ANR如果服务器不响应?什么想法?
Does the Activity get destroyed? Does the app stay awake and might go into ANR if the server doesn't respond? any thoughts?
修改
我试着这样做,而不是,但有一个 android.os.NetworkOnMainThreadException
。
I tried doing this instead but got a android.os.NetworkOnMainThreadException
.
new Runnable() {
@Override
public void run() {
JSONObject req = new JSONObject();
try {
req.put("actionKey", "UserPresenceInactive");
req.put("userId", theUser.userId);
new ServerRequest().execute(req); //Run an AsyncTask
} catch (JSONException e) {
e.printStackTrace();
}
}
}.run();
更新#2
,而不是的Runnable
的伎俩!
推荐答案
是在活动
被破坏,但的AsyncTask
正在做的工作(在后台工作)。不会有任何 ANR
,因为你没有做对UI任何背景的东西。如果更新后的的AsyncTask
你的UI任何视图完成那么就有一个空指针异常
AFAIK。但是,这不会是在运行的AsyncTask一个好主意的onDestroy()
。
Yes the Activity
gets destroyed but the AsyncTask
is doing its job(working in background). There won't be any ANR
because you are not doing any background stuff on the UI. If you are updating any view on your UI after AsyncTask
is completed then there would a NULLPOINTER Exception
AFAIK. But, this would not be a good idea to run AsyncTask in onDestroy()
.
这篇关于在的onDestroy AsyncTask.execute的影响的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!