如何正确清理活动中的位置侦听器
我有一个实现 LocationListener 的活动。
public class MyActivity extends MapActivity implements LocationListener
在我的活动中,我在 onCreate() 中注册了一个位置监听器
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, minTime, distance, this);
。在 onDestroy 方法中,我删除了位置监听器的注册。
@Override
protected void onDestroy() {
Utils.addDebugMsg(this,"onDestroy");
lm.removeUpdates(this);
super.onDestroy();
}
在我的应用程序中,我可以更改 minTime 和距离,因此我像这样重新初始化侦听器:
private void initializeGpsListener() {
lm.removeUpdates(this);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, minTime, distance, this);
}
出于调试目的,每当启用提供程序(在本例中为 GPS)时,我都会在屏幕上写入一些内容。
@Override
public void onProviderEnabled(String provider) {
Utils.addDebugMsg(this,"onProviderEnabled : " + provider);
}
我注意到,有时,我的活动(或位置侦听器)的多个实例被“保留”。每次我打开 GPS 提供程序时,我不会看到 1 个语句“onProviderEnabled : GPS”,而是看到我的 Activity 的多个不同实例打印此行(全部同时)。
如何清理这些侦听器(=我的活动),并确保在整个应用程序中只有 1 个侦听器保持活动状态。
I have an Activity that implements LocationListener.
public class MyActivity extends MapActivity implements LocationListener
In my activity, I register a locationlistener in the onCreate()
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, minTime, distance, this);
In the onDestroy method, I'm removing the registration for my locationlistener.
@Override
protected void onDestroy() {
Utils.addDebugMsg(this,"onDestroy");
lm.removeUpdates(this);
super.onDestroy();
}
In my application, I can change the minTime and distance, so I re-initialize my listener like this :
private void initializeGpsListener() {
lm.removeUpdates(this);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, minTime, distance, this);
}
For debugging purposes, I write something to the screen whenever a provider is enabled (in this case GPS).
@Override
public void onProviderEnabled(String provider) {
Utils.addDebugMsg(this,"onProviderEnabled : " + provider);
}
What I noticed is that sometimes, multiple instances of my activity (or locationlistener) are "kept around". Each time I turn the GPS provider on, instead of seeing 1 statement "onProviderEnabled : GPS", I see several different instances of my Activity printing this line (all at the same time).
How do I clean up these listeners ( = my activities), and make sure that only 1 remains active throughout the application.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
该 Activity 实现了 OnSharedPreferenceChangeListener。
在 onCreate 期间,该 Activity 被注册为 PreferenceChangelistener,但在 onDestroy() 中并未取消注册。
因此,即使在活动被销毁后,仍然存在对该活动的引用,从而导致重复消息。
The Activity implemented OnSharedPreferenceChangeListener.
During onCreate, the activity was registered as a PreferenceChangelistener, but not unregistered in the onDestroy().
As such, even after the activity was destroyed, there was still a reference to the activity, causing the duplicate messages.