我正在尝试编写一个服务来获取 Gear Live 上的心率,按照这里的问题 Get Heart Rate from "Sensor" Samsung Gear Live
如果我把这部分放在
Log.d(TAG, "prepare to call getSystemService");
mSensorManager = ((SensorManager)getSystemService(SENSOR_SERVICE));
Log.d(TAG, "after calling getSystemService");
在 Activity 的 onCreate()
中,它工作正常。但如果我将其移至服务,它就会抛出 NPE。我试图在 `getSystemService 前面添加 this.
,但没有帮助。任何提示,谢谢
最佳答案
我想通了,原因是在getSystemService
里面,调用了这个函数:
@Override
public Object getSystemService(String name) {
return mBase.getSystemService(name);
}
其中 mBase
为空。这是一个 Context
对象。所以我不得不将启动服务的 Activity 的上下文放在 onCreate()
中。代码如下:
public HeartRateMonitorService(Context context){
super();
mBaseConext = context;
}
@Override
public void onCreate() {
super.onCreate();
attachBaseContext(mBaseConext);
}
我不确定这是最佳解决方案,但它是一种解决方法。
关于android - 在服务中调用 getSystemService,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24970677/