SensorEventListener in separate thread

后端 未结 5 945
广开言路
广开言路 2020-12-05 15:11

This seems like a basic question, but after searching for a while and playing with it, I\'ve come to the point where some help would be appreciated. I would like to have a

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-05 15:39

    A little late, but if others still want to know, here is a good way to achieve this. As always when multithreading, make sure you know what you are doing and take the time to so it right, to avoid those weird errors. Have fun!

    Class members:

    private HandlerThread mSensorThread;
    private Handler mSensorHandler;
    

    in OnCreate or when registering:

    mSensorThread = new HandlerThread("Sensor thread", Thread.MAX_PRIORITY);
    mSensorThread.start();
    mSensorHandler = new Handler(mSensorThread.getLooper()) //Blocks until looper is prepared, which is fairly quick
    yourSensorManager.registerListener(yourListener, yourSensor, interval, mSensorHandler);
    

    When unregistering, also do:

    mSensorThread.quitSafely();
    

提交回复
热议问题