AsyncTask will not stop running even after onPostExecute completes and blocks activity from being GC'd
My activity does a lot of network I/O, so I start an AsyncTask (since you can not do network I/O on the UI thread) to accomplish this. My problem is that the when I call finish() to exit my application, the app is never garbage collected and continues to run in the background. I am assuming (perhaps incorrectly) that the task is never GC'd because the AsyncTasks are still running as the Eclipse debug window shows me. I have read everything I can find on this and it appears to be a problem without a solution.
Here are the details:
in OnCreate I create a MessageHandler as follows:
mMessageHandler = new Handler()
{
@Override
public synchronized void handleMessage(Message msg)
{
switch( (int)msg.arg1)
{
case kMessageDoSomething:
doSomething();
break;
.
.
I have a class for each AsyncTask, for example in myAsyncTask.java
public class myAsyncTask extends AsyncTask<Void, Object, Object>
{
@Override
protected Object doInBackground(Void... params)
{
doSomeNetworkIO();
return null;
}
@Override
protected void onPostExecute(Object result)
{
super.onPostExecute( result );
m开发者_Python百科sg = new Message();
msg.arg1 = MyActivity.getInstance().kMessageDoSomething;
MyActivity.getInstance().mMessageHandler.sendMessage( msg );
}
and back in myActivity
new myAsyncTask().execute();
in the method doSomthing() I check the AsyncTask.Status of myAsyncTask and it is FINISHED, yet the debugger still shows the task as running and when I call finish() myActivity never terminates unless I use AppKiller to kill it manually.
My real question here is, am I chasing a red herring? that is does the presence of running threads stop the activity from being garbage collected?
The AsyncTask has a thread pool, so even if your work is finished threads are not terminated, that is probably what you are seeing in the debugger. The pool is shut down by finalize()
, so it doesn't shut down until the object is GC-ed. What you might want to do is make sure your AsyncTask doesn't hold a reference to the activity and vice versa. You can detach them onDestroy()
.
Keep in mind that regardless of GC, if Android is low on memory, it will just terminate the process of your unused activity, so memory will be eventually reclaimed.
精彩评论