Get Context in a Service

Get Context in a Service

Service is a Context

Android getContext on a background Service

Service extends Context. You can use this, where this is the reference to the Service instance.

Putting more details on my comment below regarding the following code of SubscribeService class:

@Override
public void onCreate() {
super.onCreate();
context = this;
context = MyApp.getContext();
}

In your Service's onCreate() context = this cannot be null by a fundamental programming paradigm.

How can I get the application context from an Android Service?

ctx.getApplicationContext().startActivity(i)

boom.

Android how get Context from specific class being in Service

Solution: 1

In that case you have to use, defaultSharedPreferences. You can access the default shared preferences instance by:

PreferenceManager.getDefaultSharedPreferences(Context context):

Example:

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);

This preference is shared across all your Activity and Service classes.

Solution: 2

You can create sharedPreference instance in your application class like:

public class MyApplication extends Application {
public static SharedPreferences preferences;

@Override
public void onCreate() {
super.onCreate();

preferences = getSharedPreferences("Preferences", MODE_PRIVATE);
}

}

And then you can manage your preferences as:

MyApplication.preferences.getString("key", "default");


Related Topics



Leave a reply



Submit