Search code examples
androidandroid-activityaccelerometersensors

Android: Can I access system services without an Activity?


I have been reading and have seen that system services cannot be accessed straight away; they must be accessed after onCreate() has been called.

I am creating a Keyboard service but I would like to access system services such as sensors. Is there a way I can do this without an activity?

I have already tried having my class inheriting InputMethodService and implementing SensorEventListener. I implement the method onSensorChanged() and tell it to print to logcat but it is never called. I have a method onCreateInputView() in which I define the sensor manager and accelerometer:

public class MyInput extends InputMethodService implements SensorEventListener {
    MyInputView MyInputView;
    private SensorManager mSensorManager;

    @Override
    public View onCreateInputView() {

        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);

        final MyInputView MyInputView = (MyInputView) getLayoutInflater().inflate(R.layout.MyInput, null);

        this.MyInputView = MyInputView;

        return MyInputView;

    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        // TODO Auto-generated method stub
        Log.d("called", "called");
    }

}

[Based on suggestions given it appears InputMethodService derives from Context and as such, onCreate() should be called...]


Solution

  • You have to not only obtain your service, but also register your event listener.

    See for example the following section from the ApiDemos project of the (legacy) SDK Samples:

     mSensorManager.registerListener(mGraphView, 
                SensorManager.SENSOR_ACCELEROMETER | 
                SensorManager.SENSOR_MAGNETIC_FIELD | 
                SensorManager.SENSOR_ORIENTATION,
                SensorManager.SENSOR_DELAY_FASTEST);
    

    In your case it is your MyInput class itself which implements the event listener, so you would pass your instance of that instead.