android - Get Context in a Service

ID : 10314

viewed : 20

Tags : androidbroadcastreceiverandroid-serviceandroid

Top 5 Answer for android - Get Context in a Service

vote vote

100

vote vote

84

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

vote vote

72

  1. Service extends ContextWrapper
  2. ContextWrapper extends Context

So....

Context context = this; 

(in Service or Activity Class)

vote vote

61

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

DataBaseManager dbm = Utils.getDataManager(this);    
vote vote

50

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

Top 3 video Explaining android - Get Context in a Service

Related QUESTION?