问题
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();
}
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?
Does the Activity get destroyed? Does the app stay awake and might go into ANR if the server doesn't respond? any thoughts?
edit
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();
UPDATE #2
using a Thread instead of a Runnable did the trick!
回答1:
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().
回答2:
The best approach would be run your AsyncTask in method such as onPause() or onSaveInstanceState() and not in onDestroy()
Looking at developer android reference:
OnPause(): This callback is mostly used for saving any persistent state the activity is editing, to present a "edit in place" model to the user and making sure nothing is lost if there are not enough resources to start the new activity without first killing this one. This is also a good place to do things like stop animations and other things that consume a noticeable amount of CPU in order to make the switch to the next activity as fast as possible, or to close resources that are exclusive access such as the camera.
In situations where the system needs more memory it may kill paused processes to reclaim resources. Because of this, you should be sure that all of your state is saved by the time you return from this function. In general onSaveInstanceState(Bundle) is used to save per-instance state in the activity and this method is used to store global persistent data (in content providers, files, etc.)
来源:https://stackoverflow.com/questions/11243056/implications-of-asynctask-execute-in-ondestroy