我对传感器监听器的取消注册感到困惑。假设我忘记取消注册一个监听器。应用程序被销毁后会发生什么?
Android操作系统会继续向应用程序发送消息吗?但是应用程序被破坏,因此其过程终止。有人可以帮忙回答这个问题吗?谢谢:))
答案 0 :(得分:5)
但是应用程序被破坏了,因此它的过程是 终止。
情况并非总是如此。在正常情况下,Android will keep your application process alive尽可能长。如果您碰巧有仍然注册的侦听器,那么这些侦听器引用的对象的旧副本(很可能是Activity的子类)可能不会被垃圾回收并继续占用宝贵的内存。传感器监听器特别糟糕,因为该框架还需要花费其他大量资源来继续提供它们。
要演示此问题,您只需在有意保留注册的传感器侦听器中打印一些日志消息即可。即使您正常退出应用程序,您也会看到日志消息将继续打印出来。然后你也可以run MAT to inspect the memory of your process,它可能会显示你的Activity对象的副本仍然在内存中挥之不去。如果您多次启动您的应用,MAT将向您显示您的活动的多个“僵尸”副本仍然存在:)
答案 1 :(得分:1)
developer.android.com明确指出
始终确保禁用您不需要的传感器,尤其是在您的活动暂停时。如果不这样做,可能会在几个小时内耗尽电池电量。请注意,当屏幕关闭时,系统不会自动禁用传感器。
http://developer.android.com/reference/android/hardware/SensorManager.html
答案 2 :(得分:0)
是的,你应该这样做,因为数据仍会发送到你的应用程序,我相信"close" (unregister)
你"opened" (registered)
的东西总是很好的编程风格。我写了一些示例方法来演示如何执行此操作:
(注意:此代码必须放在实现SensorEventListener, OnTouchListener, OnKeyListener
)
/**
* <b><i>public void useAccelerometer(boolean use)</i></b>
* <br>
* Since: API 1
* <br>
* <br>
* Set if you would like to enable the use of the accelerometer.
*
* @param use
* <br>
* True will enable the use of the accelerometer.
* <br>
* False will disable the use of the accelerometer.
*
*/
public void useAccelerometer(boolean use) {
if(use == true) {
manager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_GAME);
if(this.logGameEngineInputLog == true) {
gameEngineLog.d(classTAG, "Accelerometer enabled");
}
}
else {
manager.unregisterListener(this, accelerometer);
if(this.logGameEngineInputLog == true) {
gameEngineLog.d(classTAG, "Accelerometer disabled");
}
}
}
/**
* <b><i>public void useTouchscreen(boolean use)</i></b>
* <br>
* Since: API 1
* <br>
* <br>
* Set if you would like to enable the use of the touch screen.
*
* @param use
* <br>
* True will enable the use of the touch screen.
* <br>
* False will disable the use of the touch screen.
*
*/
public void useTouchscreen(boolean use) {
if(use == true) {
view.setOnTouchListener(this);
if(this.logGameEngineInputLog == true) {
gameEngineLog.d(classTAG, "Touchscreen enabled");
}
}
else {
view.setOnTouchListener(null);
if(this.logGameEngineInputLog == true) {
gameEngineLog.d(classTAG, "Touchscreen disabled");
}
}
}
/**
* <b><i>public void useKeyboard(boolean use)</i></b>
* <br>
* Since: API 1
* <br>
* <br>
* Set if you would like to enable the use of the keyboard.
*
* @param use
* <br>
* True will enable the use of the keyboard.
* <br>
* False will disable the use of the keyboard.
*
*/
public void useKeyboard(boolean use) {
if(use == true) {
view.setOnKeyListener(this);
if(this.logGameEngineInputLog == true) {
gameEngineLog.d(classTAG, "Keyboard enabled");
}
}
else {
view.setOnKeyListener(null);
if(this.logGameEngineInputLog == true) {
gameEngineLog.d(classTAG, "Keyboard disabled");
}
}
}
答案 3 :(得分:0)
即使应用程序被销毁,传感器也会继续工作,因为它未被注册。如果您注册传感器,那么您也必须取消注册...