I have the following piece of code:
public class DumpLocationLog extends Thread {
LocationManager lm;
LocationHelper loc;
public void onCreate() {
loc = new LocationHelper();
lm = (LocationManager) Context.getSystemService(Context.LOCATION_SERVICE);
}
public void run() {
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 500.0f, loc);
}
}
I want it to be run from a remote service but in the line lm = (LocationManager) Context.getSystemService(Context.LOCATION_SERVICE); I get a NullPointerException error of course, because the context is null.
How can I get the context here? getBaseContext() or getApplicationContext() does not work.
A
Threadwould not have any direct access to aContextby default; you would have to pass it in. A Thread also does not need anonCreatemethod (which I guess you are calling manually) – I would just change it to a constructor. You can just pass in a Context in the constructor of the Thread:You would instantiate it with
new DumpLocationLog(this);if used from inside aService(a Service is a subclass of Context, sothisworks here). You start the thread by calling thestart()method.