Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android : How get the current Application Context in AsyncTask?

Tags:

android

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

like image 741
user1364017 Avatar asked Apr 29 '12 10:04

user1364017


People also ask

How do you know when AsyncTask is done?

Use getStatus() to get the status of your AsyncTask . If status is AsyncTask. Status. RUNNING then your task is running.

What is the problem with AsyncTask in Android?

In summary, the three most common issues with AsyncTask are: Memory leaks. Cancellation of background work. Computational cost.

Why did AsyncTask get deprecated?

This class was deprecated in API level 30. AsyncTask was intended to enable proper and easy use of the UI thread. However, the most common use case was for integrating into UI, and that would cause Context leaks, missed callbacks, or crashes on configuration changes.

What is the replacement of AsyncTask?

Alternative 1: Using Executor and Handler The executor will help in performing any task in the background and the handler will help to make UI changes.


2 Answers

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.

like image 107
Flo Avatar answered Nov 15 '22 00:11

Flo


You can pass the whole Activity and the use getApplicationContext() inside the AsyncTask.

like image 27
Hauleth Avatar answered Nov 14 '22 23:11

Hauleth