我有下面这段code的:
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);
}
}
我希望它是从一个远程服务,但在运行行流明=(的LocationManager)Context.getSystemService(Context.LOCATION_SERVICE);
我收到了 NullPointerException异常
当然是错误的,因为背景
为null。
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.
我怎么能在这里得到的背景? getBaseContext()
或 getApplicationContext()
不起作用。
How can I get the context here? getBaseContext()
or getApplicationContext()
does not work.
推荐答案
A 发
不会有一个的任何直接访问上下文
默认;你将不得不通过它在一个线程也不需要的onCreate
方法(我猜你是手动调用) - 我只是将其更改为一个构造函数。你可以通过在语境中的Thread的构造函数:
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);
}
}
如果从服务里使用
(服务是;
您将与新DumpLocationLog(本)实例化它语境的一个子类,所以
这个
在这里工作)。您可以通过调用开始启动线程()
方法。
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.
相关推荐
最新文章