Get Context in a Service – Dev

The best answers to the question “Get Context in a Service” in the category Dev.

QUESTION:

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?

ANSWER:

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

ANSWER:

Service is a Context

ANSWER:

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

DataBaseManager dbm = Utils.getDataManager(this);   

ANSWER:

  1. Service extends ContextWrapper
  2. ContextWrapper extends Context

So….

Context context = this;

(in Service or Activity Class)