I have an Activity that contains an AsyncTask as an inner class (as I have seen in most examples). If I fire the AsyncTask and then pause the Activity by navigating away from it, the AsyncTask continues to execute. As I understand it, this is normal and expected behavior.
There is a member variable in the Activity that is being accessed by a method call from the AsyncTask. I just got a NullPointerException on it while the AsyncTask was executing in the background while its Activity was paused, which seems to me that it was collected by the GC when the Activity was paused. It would seem to me that the object should not be considered out of scope. There is code still running in the Activity, so why would the Activity's member variables start getting cleaned up already?
What is the recommended usage of Activity member variables being accessed via AsyncTasks that are inner classes of the Activity?
Here is a sample of the kind of relationships my objects have
public class MyActivity {
MyCustomService myCustomService;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.some_layout);
myCustomService = ServiceLoc开发者_运维百科ator.getInstance(MyCustomService.class);
}
private class FetchDataTask extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... arg0) {
String data = someOtherService.fetchSomeData();
return data;
}
@Override
protected void onPostExecute(String result) {
refreshControls(result);
}
}
private void refreshControls(String result) {
// this is where the object is null after aggressive cleanup
myCustomService.someMethod();
}
I don't really understand what is causing the NullPointerException
.
But you might want to check my answer here for a AsyncTask
which is not a inner class of the activity but static
. Inner async tasks which are started are leaking the context / activity as long as they are running. This might be no problem for short running tasks but if it stucks or performs for a long time it is leaking memory for that time.
This might imply the answer to your question...
精彩评论