Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the Application Context

This might be a simple question but I just wanted to make sure I am right.

In my android application I have a constructor that uses:

activity.getApplicationContext()

The activity is passed into the constructor as a parameter.

The problem is that I am calling this class from a Service. If I make a second constructor which accepts the Service as a parameter and uses service.getApplicationContext? Will I get the same application context?

like image 458
gtdevel Avatar asked Sep 09 '25 16:09

gtdevel


2 Answers

The easiest way to get the application context is:

Create a class App that extends android.app.Application

public class App extends Application {
    public static Context context;

    @Override public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
    }
}

Modify your AndroidManifest.xml 's <application> tag to have the attribute android:name="your.package.name.App".

Any time you need the application context, just get it from App.context.

Application is always initialized first whether your process runs, whether it's an activity, a service, or something else. You will always have access to the application context.

like image 69
Randy Sugianto 'Yuku' Avatar answered Sep 12 '25 06:09

Randy Sugianto 'Yuku'


Will I get the same application context?

Yes. You can check the android documentation, they have provided

 getApplicationContext()

Return the context of the single, global Application object of the current process.

So it should not be changed for the whole application process.

Please also take a note of this:

getApplicationContext() generally should only be used if you need a Context whose lifecycle is separate from the current context, that is tied to the lifetime of the process rather than the current component.

Correct me if I'm wrong.

Thanks

like image 32
bHaRaTh Avatar answered Sep 12 '25 04:09

bHaRaTh