![](/img/trans.png)
[英]NullpointerException when calling getSystemService(Context.LOCATION_SERVICE) and onLocationChanged not called
[英]calling getSystemService inside a service
我正在尝试编写一个在Gear Live上获取心率的服务,以下是此处的问题, 请从“传感器” Samsung Gear Live获取心率
如果我把这部分
Log.d(TAG, "prepare to call getSystemService");
mSensorManager = ((SensorManager)getSystemService(SENSOR_SERVICE));
Log.d(TAG, "after calling getSystemService");
在活动的onCreate()
上,它可以正常工作。 但是,如果我将其移至服务,则会抛出NPE。 我试图添加this.
在getSystemService前面,没有帮助。 任何提示,谢谢
我知道了,原因是在getSystemService
内部,有一个对此函数的调用:
@Override
public Object getSystemService(String name) {
return mBase.getSystemService(name);
}
其中mBase
为null。 这是一个Context
对象。 因此,我不得不将启动服务的活动的上下文放在onCreate()
。 代码如下:
public HeartRateMonitorService(Context context){
super();
mBaseConext = context;
}
@Override
public void onCreate() {
super.onCreate();
attachBaseContext(mBaseConext);
}
我不确定这是否是最佳解决方案,但这是一种解决方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.