calling getSystemService inside a service

半腔热情 提交于 2019-12-04 05:13:05

问题


I'm trying to write a service that get the heart rate on Gear Live, following the question here Get Heart Rate from "Sensor" Samsung Gear Live

If I put this part

    Log.d(TAG, "prepare to call getSystemService");
    mSensorManager = ((SensorManager)getSystemService(SENSOR_SERVICE));
    Log.d(TAG, "after calling getSystemService");

at onCreate() of an activity, it works fine. But if I move that to a Service, it throws a NPE. I tried to add this. in front of `getSystemService, doesn't help. Any tip, thanks


回答1:


I figured it out, the reason is that inside getSystemService, there's a call to this function:

 @Override
public Object getSystemService(String name) {
    return mBase.getSystemService(name);
}

which has mBase as null. This is a Context object. So I had to put the context of the activity that start the service in onCreate(). Code below:

 public HeartRateMonitorService(Context context){
    super();
    mBaseConext = context;
}


@Override
public void onCreate() {
    super.onCreate();
    attachBaseContext(mBaseConext);
}

I'm not sure this is the optimal solution, but it is a workaround.



来源:https://stackoverflow.com/questions/24970677/calling-getsystemservice-inside-a-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!