如何在停止服务后从传感器取消注册侦听器?

时间:2012-03-17 14:27:50

标签: android android-sensors

我正在创建一个应用程序,当按下“开始”按钮时启动服务,并在按下“停止”按钮时停止它。在服务中,我为传感器ACCELEROMETER注册一个监听器,以便获得x,y,z轴的加速度计值..但是当我停止我的应用程序并从传感器取消注册监听器时,即使这样我也得到了加速度计值。 / p>

以下是代码:

// 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
    }
};

}

任何人都可以帮帮我吗?

1 个答案:

答案 0 :(得分:0)

您的应用可能不会立即调用操作系统

onDestroy()。将stopListening()来电置于onPause()startListening() onResume()功能中。通过这种方式,您可以确保应用程序注册并使用传感器取消注册。