android 如何在停止服务后从传感器注销侦听器?

daupos2t  于 2024-01-04  发布在  Android
关注(0)|答案(1)|浏览(159)

我正在创建一个应用程序,当按下“开始”按钮时启动服务,当按下“停止”按钮时停止服务。在服务中,我为传感器ACCELEROMETER注册了一个侦听器,以便我获得x,y,z轴的加速度计值。
代码如下:

  1. // Service
  2. public class Accel extends Service
  3. {
  4. private static Context CONTEXT;
  5. private static Sensor sensor;
  6. private static SensorManager sensorManager;
  7. private static boolean running = false;
  8. @Override
  9. public void onCreate()
  10. {
  11. }
  12. // code to execute when the service is shutting down
  13. @Override
  14. public void onDestroy()
  15. {
  16. if (isListening())
  17. stopListening();
  18. }
  19. // code to execute when the service is starting up
  20. @Override
  21. public void onStart(Intent intent, int startid)
  22. {
  23. CONTEXT = this;
  24. startListening(this);
  25. }
  26. public static Context getContext()
  27. {
  28. return CONTEXT;
  29. }
  30. // Returns true if the manager is listening to orientation changes
  31. public static boolean isListening()
  32. {
  33. return running;
  34. }
  35. //Unregisters listeners
  36. public static void stopListening()
  37. {
  38. running = false;
  39. sensorManager.unregisterListener(sensorEventListener, sensor);
  40. }
  41. /**
  42. * Registers a listener and start listening
  43. * @param accelerometerListener
  44. * callback for accelerometer events
  45. */
  46. public static void startListening(AccelerometerListener accelerometerListener)
  47. {
  48. sensorManager = (SensorManager) getContext().getSystemService(Context.SENSOR_SERVICE);
  49. List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER);
  50. if (sensors.size() > 0)
  51. {
  52. sensor = sensors.get(0);
  53. running = sensorManager.registerListener(sensorEventListener, sensor, SensorManager.SENSOR_DELAY_GAME);
  54. listener = accelerometerListener;
  55. }
  56. }
  57. /**
  58. * The listener that listen to events from the accelerometer listener
  59. */
  60. private static SensorEventListener sensorEventListener =
  61. new SensorEventListener()
  62. {
  63. public void onAccuracyChanged(Sensor sensor, int accuracy) {}
  64. public void onSensorChanged(SensorEvent event)
  65. {
  66. // the code to perform on sensor change
  67. }
  68. };

字符串
}
有人能帮帮我吗?”

kuhbmx9i

kuhbmx9i1#

onDestroy()可能不会立即被应用上的操作系统调用。将stopListening()调用放入onResume()函数中的onPause()startListening()。这样就可以保证应用在传感器上注册和注销。

相关问题