问题
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.
回答1:
A Thread would not have any direct access to a Context by default; you would have to pass it in. A Thread also does not need an onCreate method (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:
public class DumpLocationLog extends Thread {
LocationManager lm;
LocationHelper loc;
public DumpLocationLog(Context context) {
loc = new LocationHelper();
lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
}
public void run() {
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 500.0f, loc);
}
}
You would instantiate it with new DumpLocationLog(this); if used from inside a Service (a Service is a subclass of Context, so this works here). You start the thread by calling the start() method.
回答2:
You could pass a valid context through the constructor, or, if your class is an inner class inside a service you could use ServiceClassName.this.getContext()
来源:https://stackoverflow.com/questions/6967221/getting-the-context-in-a-thread-called-by-a-service