1

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

Community
  • 1
  • 1
EyeQ Tech
  • 7,198
  • 18
  • 72
  • 126

1 Answers1

2

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.

EyeQ Tech
  • 7,198
  • 18
  • 72
  • 126
  • how about calling getSystemService with the provided context? such as context.getSystemService? – josephus Jul 27 '14 at 23:45
  • @josephus, just tried, that works just fine as well. – EyeQ Tech Jul 27 '14 at 23:49
  • 1
    This is unwise. You should not be trying to set the service's Context to one passed in externally (rather you should be letting your Service instance properly initialize). If you want to use an external Context for this particular method, then do so explicitly. – Chris Stratton Jul 27 '14 at 23:56
  • @ChrisStratton, I genuinely believe there's a loophole with my hack. However, so far I haven't found a working solution, can you point me to some resource? I need a decent solution badly. – EyeQ Tech Jul 27 '14 at 23:59
  • I see, but that `context` is also an activity, which is passed in, then call `context.getSystemService()`, I meant is there another way to create the service context since the activity may die, but the service must keep running. – EyeQ Tech Jul 28 '14 at 05:36
  • From this it looks as though you are creating your `Service` by explicitly calling `new` for the class. You do not want to do that. You need to use `startService()` or `bindService()` to start your services. Otherwise the framework class (`Service`) will not go through its lifecycle properly. – Larry Schiefer Jul 28 '14 at 14:39