문제

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...]

도움이 되었습니까?

해결책 2

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.

다른 팁

getSystemService() can be called on any instance of Context, and since InputMethodService traces its origins back to Context, you can obtain access to system services in it, as long as your call is after the onCreate() method.

This works just like when you use the Accelerometer from a background service. Having a visible Activity is not a requirement for getting access to system Services.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top