Get Context in a Service
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.
Service
extendsContextWrapper
ContextWrapper
extendsContext
So....
Context context = this;
(in Service or Activity Class)
Service is a Context
Service
extends ContextWrapper
which extends Context
. Hence the Service
is a Context
.
Use 'this'
keyword in the service.