• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps memory allocated in AsyncTask persists creating leak

I am working on a small game where I want a loading screen to appear when loading the next level. I have accomplished this using an AsycTask, the idea being that I draw the loading screen first and call invalidate(), then I start an AsyncTask which loads a new map object in the background so that the UI thread can continue and draw the loading screen. When complete, the map is returned and the loading screen is removed.

Code:
public class LoadTask extends AsyncTask<String,Integer,Map>{
    protected Map doInBackground(String... mapName) {
        return new Map(mapName[0]);
    }

    protected void onPostExecute(Map newMap) {
    	//Set newMap as active Map
        //Remove loading screen and draw newMap
    }
}
	
//Draw Loading Screen
//Call invalidate 
//Execute a LoadTask to that UI thread can continue to draw loading screen
new LoadTask().execute(mapName);

This works, however; the Map object which i create in doInBackground seems to persist, so after the 4th level, even though I only have references to 1 Map, I have 4 Map objects in memory (I got this information by doing a heap dump after each level load). At this point I get an OutOfMemoryError.

Something else to note is that after the 4th level load, under the Threads tab in the DDMS i see:
AsyncTask#1
AsyncTask#2
AsyncTask#3
AsyncTask#4
all with a status of "wait"

Any ideas here would be greatly appreciated!
 
Well I have found a solution that works, although I cannot say I understand why the first way didn't work. All I had to do was set my new map in the doInBackground function instead of passing it through to onPostExecute (which I thought was the whole point of using AsyncTasks)

Code:
public class LoadTask extends AsyncTask<String,Void,Void>{
    protected Map doInBackground(String... mapName) {
        Map newMap = new Map(mapName[0]);
        //Set newMap as active Map
        return null;
    }

    protected void onPostExecute(Void tmp) {
        //Remove loading screen
    }
}
	
//Draw Loading Screen
//Call invalidate 
//Execute a LoadTask to that UI thread can continue to draw loading screen
new LoadTask().execute(mapName);
 
Back
Top Bottom