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

前端 未结 3 1077
醉梦人生
醉梦人生 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 11:58

    If it uses a SensorEventListener, then what's the purpose of the Handler?

    If I had to guess, it is so you can get your sensor events delivered on a background thread (e.g., a HandlerThread). By default, sensor events are delivered on the main application thread, which is fine in some cases.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-06 12:18

    1) If it uses a SensorEventListener, then what's the purpose of the Handler? if you run it on the main thread , and you're doing some heavy calculations you will slow down the main UI to be unresponsive.Always write your long running tasks in a separate thread, to avoid ANR.

    Here is an example http://stacktips.com/tutorials/android/android-service-example

    0 讨论(0)
提交回复
热议问题