Android : How get the current Application Context in AsyncTask?

I create an application with several activities and i have an AsyncTask outside any activity which is launched at the begining of the application life. My question is how can i get the current Application Context in the Asynctask class? Thank's for your answers

asked Apr 29, 2012 at 10:21 user1364017 user1364017 129 1 1 silver badge 10 10 bronze badges

2 Answers 2

Pass the context as an parameter to you AsyncTask's constructor and store it there as a member. But take care which context type you pass to the constructor.

When the task might run over the lifetime of an Activity then you should pass an Application context instead of an Activity context. When the task only runs for the lifetime of an Activity you can pass the Activity object as context.

answered Apr 29, 2012 at 10:30 27.4k 16 16 gold badges 89 89 silver badges 126 126 bronze badges

The problem is that the current Activity will change and therefore my parameter of my AsyncTask's will be wrong

Commented Apr 29, 2012 at 10:47

So that sound's like the task's life time is bound to the activity's life time. Then you can use the Activity object as an context but you should cancel the task in the onDestroy() method of the activity so the old Activity object could get garbage collected.

Commented Apr 29, 2012 at 10:56

The task's life is bound in singleton class which is instancied by an activity. So the task's continue after the activity life

Commented Apr 29, 2012 at 11:01 My task is independant and his life is egal to the application life. Commented Apr 29, 2012 at 11:04

Ok, so when you activity calls the singleton it has to pass the application context (getApplicationContext()) with the call so the singleton could use it to create the AsyncTask with the correct context type. I still don't under stand what you meant with The problem is that the current Activity will change and therefore my parameter of my AsyncTask's will be wrong . This seems not to be related to the initial question.