SensorEventListener doesn't get unregistered with unregisterListener() method

后端 未结 7 1555
一生所求
一生所求 2020-12-15 16:37

I have very simple Android app: in activity I have a button and I start/stop the OrientationListener. However, after unregistering it, in ddms I can still see the thread

7条回答
  •  半阙折子戏
    2020-12-15 17:19

    I faced similar issue.

    Workaround to stop the sensor.

    I used a static boolean mIsSensorUpdateEnabled. Set it to 'false' when you want to stop getting values from sensors. And in onSensorChanged() method, check the value of the boolean variable and again make to call to unregister the sensors. And this time, it works. The sensors would be unregistered and you will no longer get onSensorChanged callback.

    public class MainActivity extends Activity implements SensorEventListener {
        private static boolean mIsSensorUpdateEnabled = false;
        private SensorManager mSensorManager;
        private Sensor mAccelerometer;
    
        @override
        protected void onCreate(){
            mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        }
    
        private startSensors(){
            mAccelerometer =  mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
            int delay = 100000; //in microseconds equivalent to 0.1 sec
            mSensorManager.registerListener(this,
                    mAccelerometer,
                    delay
            );
            mIsSensorUpdateEnabled =true;
        }
    
        private stopSensors(){
            mSensorManager.unregisterListener(this, mAccelerometer);
            mIsSensorUpdateEnabled =false;
        }
    
    
        @Override
        public void onSensorChanged(SensorEvent event) {
            if (!mIsSensorUpdateEnabled) {
                stopSensors();
                Log.e("SensorMM", "SensorUpdate disabled. returning");
                return;
            }
            //Do other work with sensor data
        }
    }
    

提交回复
热议问题