Android LocationListener 崩溃
我正在尝试通过切换按钮启用/禁用 GPS 服务。应用程序启动时按钮未选中,并且 GPS 服务被禁用(理应如此)。它们成功打开并且工作得很好但是当我再次关闭它时,它崩溃了。这是代码:
final LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
final LocationListener locationListener = null;
final ToggleButton gpsButton = (ToggleButton) findViewById(R.id.gpsButton);
gpsButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if (gpsButton.isChecked()) {
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
//doing some stuff with locations
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, seconds, 0, locationListener);
}
else {
locationManager.removeUpdates(locationListener);
}
}
I'm trying to enable/disable GPS services by a ToggleButton. The app starts with the button unchecked, and GPS services are disabled (as they should be). They turn on successfully and works great BUT when I turn it off again, it crashes. Here's the code:
final LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
final LocationListener locationListener = null;
final ToggleButton gpsButton = (ToggleButton) findViewById(R.id.gpsButton);
gpsButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if (gpsButton.isChecked()) {
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
//doing some stuff with locations
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, seconds, 0, locationListener);
}
else {
locationManager.removeUpdates(locationListener);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您在
onClickListener
之外声明locationListener
,但随后在用户单击按钮时创建一个新的本地locationListener
变量。当您尝试从中删除更新时,它仍然为
null
,因为您创建了不同的变量。去掉onClick
方法中locationListener
的类型声明,这样就变成了You are declaring the
locationListener
outside of theonClickListener
, but then creating a new locallocationListener
variable when the user clicks the button.It is still
null
when you try to remove updates from it because you have created a different variable. Remove the type declaration fromlocationListener
in theonClick
method, so it becomes