Get Context in a Service

Viewed 154991

Is there any reliable way to get a Context from a Service?

I want to register a broadcast receiver for ACTION_PHONE_STATE_CHANGED but I don't need my app to always get this information, so I don't put it in the Manifest.

However, I can't have the broadcast receiver be killed by the GC when I need this information so I'm registering the broadcast receiver in a Service.

Hence, I need a Context to to call registerReceiver(). When I no longer need the ACTION_PHONE_STATE_CHANGED I unregister it.

Any tips?

7 Answers

just in case someone is getting NullPointerException, you need to get the context inside onCreate().

Service is a Context, so do this:

private Context context;

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

Note:

Read: "Do not place Android context classes in static fields; this is a memory leak (and also breaks Instant Run)" Do you know what context classes are? Activity is one of them, and you should not store Activity as a static field, (or it will leak memory). However, you can store Context (as long as it is the application context) as a static field, since it outlives everything.

As Service is already a Context itself

you can even get it through:

Context mContext = this;

OR

Context mContext = [class name].this;  //[] only specify the class name
// mContext = JobServiceSchedule.this; 

If you want service context then use this keyword. if you want activity context you can access that by using by making static variable like this

public static Context context;

in the activity onCreate()

context=this;

now you can access that context inside the service

Related