SensorManager.registerListener (.., Handler handler), example please?

前端 未结 3 1084
醉梦人生
醉梦人生 2021-02-06 11:14

I don\'t understand how to use this method,

sensorManager.registerListener(SensorEventListener listener, Sensor sensor, int rate, Handler handler);

(Documentati

3条回答
  •  被撕碎了的回忆
    2021-02-06 12:12

    Here you have an example:

    SensorManager mSensorMgr = (SensorManager) mContext.getSystemService(Context.SENSOR_SERVICE);
    
    HandlerThread mHandlerThread = new HandlerThread("sensorThread");
    
    mHandlerThread.start();
    
    Handler handler = new Handler(mHandlerThread.getLooper());
    
    mSensorMgr.registerListener(this, mSensorMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
                        SensorManager.SENSOR_DELAY_FASTEST, handler);
    

    From the source code of android SensorManager's class you can see that the registerListener() extract the Looper of your Handler to create a new handler with this looper where it call the onSensorChanged method.

    If you don't pass your handler,the SensorManager will use the main application thread.

提交回复
热议问题