Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Context in a Service

People also ask

How do I find the service context?

You can get ServiceContext using following code in servlet: ServiceContext serviceContext = new ServiceContext(); serviceContext. setScopeGroupId(myGroupId);

Does service have context android?

Services can be started with Context. startService() and Context. bindService() . Note that services, like other application objects, run in the main thread of their hosting process.

How do I get application context from activity?

You can go for getApplicationContext() if you wanna get context of whole application. If you want to get context of current class you can use getBaseContext() instead.


Service is a Context


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


  1. Service extends ContextWrapper
  2. ContextWrapper extends Context

So....

Context context = this;

(in Service or Activity Class)


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

DataBaseManager dbm = Utils.getDataManager(this);   

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;
}

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;