获取服务调用的线程中的上下文
我有以下代码:
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);
}
}
我希望它从远程服务运行,但在 lm = (LocationManager) Context.getSystemService(Context.LOCATION_SERVICE); 行中我得到一个 NullPointerException 当然是错误,因为 context
为空。
我怎样才能得到这里的上下文? getBaseContext()
或 getApplicationContext()
不起作用。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
默认情况下,
Thread
无法直接访问Context
;线程也不需要 onCreate 方法(我猜你是手动调用的) - 我只需将其更改为构造函数。您只需在线程的构造函数中传入 Context:如果从
Service
内部使用(Service 是一个Context 的子类,所以this
在这里起作用)。您可以通过调用start()
方法来启动线程。A
Thread
would not have any direct access to aContext
by default; you would have to pass it in. A Thread also does not need anonCreate
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:You would instantiate it with
new DumpLocationLog(this);
if used from inside aService
(a Service is a subclass of Context, sothis
works here). You start the thread by calling thestart()
method.您可以通过构造函数传递有效的上下文,或者,如果您的类是服务内的内部类,您可以使用 ServiceClassName.this.getContext()
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()