How to unregister a listener from a sensor after s

2019-04-27 08:20发布

I'm creating an app that starts a service when "Start" button pressed and stops it when "Stop" button is pressed. in the service, I register a listener for sensor ACCELEROMETER so that I get the accelerometer values of x,y,z axes.. but when I stop my application and unregister the listener from the sensor, even then I get my accelerometer values.

Here's the code:

// Service
public class Accel extends Service
{
    private static Context CONTEXT; 
    private static Sensor sensor;
    private static SensorManager sensorManager;
    private static boolean running = false;

    @Override
    public void onCreate()
    {
    }

    // code to execute when the service is shutting down
    @Override
    public void onDestroy()
    {
        if (isListening())
            stopListening();
    }

    // code to execute when the service is starting up 
    @Override
    public void onStart(Intent intent, int startid)
    {
        CONTEXT = this;
        startListening(this);
    }

    public static Context getContext()
    {
        return CONTEXT;
    }

    // Returns true if the manager is listening to orientation changes
    public static boolean isListening()
    {
        return running;
    }

    //Unregisters listeners
    public static void stopListening()
    {
        running = false;
        sensorManager.unregisterListener(sensorEventListener, sensor);
    }

    /**
     * Registers a listener and start listening
     * @param accelerometerListener
     *             callback for accelerometer events
     */
    public static void startListening(AccelerometerListener accelerometerListener)
    {
        sensorManager = (SensorManager) getContext().getSystemService(Context.SENSOR_SERVICE);
        List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER);
        if (sensors.size() > 0)
        {
            sensor = sensors.get(0);
            running = sensorManager.registerListener(sensorEventListener, sensor, SensorManager.SENSOR_DELAY_GAME);
            listener = accelerometerListener;
        }
    }

    /**
     * The listener that listen to events from the accelerometer listener
     */
    private static SensorEventListener sensorEventListener = 
    new SensorEventListener()
    {
    public void onAccuracyChanged(Sensor sensor, int accuracy) {}
    public void onSensorChanged(SensorEvent event)
    {
                // the code to perform on sensor change
    }
};

}

Can anyone please help me out??

1条回答
做自己的国王
2楼-- · 2019-04-27 08:33

onDestroy() may not be called by the OS on your app straight away. Place your stopListening() call into onPause(), and startListening() in your onResume() functions. This way you are guaranteed to have the app register and unregister itself with the sensors.

查看更多
登录 后发表回答