Get Context in a Service

AndroidBroadcastreceiverAndroid Service

Android Problem Overview


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?

Android Solutions


Solution 1 - Android

Solution 2 - Android

Service extends ContextWrapper which extends Context. Hence the Service is a Context. Use 'this' keyword in the service.

Solution 3 - Android

  1. Service extends ContextWrapper
  2. ContextWrapper extends Context

So....

Context context = this;

(in Service or Activity Class)

Solution 4 - Android

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

Service is a Context, so do this:

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

Solution 5 - Android

Since Service is a Context, the variable context must be this:

DataBaseManager dbm = Utils.getDataManager(this);	

Solution 6 - Android

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; 

Solution 7 - Android

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser123321View Question on Stackoverflow
Solution 1 - AndroidmibollmaView Answer on Stackoverflow
Solution 2 - Androiduser2138983View Answer on Stackoverflow
Solution 3 - AndroidHardik GajeraView Answer on Stackoverflow
Solution 4 - AndroidEcclesiaste PandaView Answer on Stackoverflow
Solution 5 - AndroidJorgesysView Answer on Stackoverflow
Solution 6 - AndroidAli Azaz AlamView Answer on Stackoverflow
Solution 7 - AndroidSaurabh DhageView Answer on Stackoverflow