gpt4 book ai didi

java - Android LocationListener 崩溃

转载 作者:行者123 更新时间:2023-11-30 09:43:30 47 4
gpt4 key购买 nike

我正在尝试通过 ToggleButton 启用/禁用 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);
}
}

最佳答案

您在 onClickListener 之外声明了 locationListener,但随后在用户单击按钮时创建了一个新的本地 locationListener 变量。

当您尝试从中删除更新时,它仍然是 null,因为您创建了一个不同的变量。去掉onClick方法中locationListener的类型声明,所以变成了

...
if (gpsButton.isChecked()) {
locationListener = new LocationListener() {
...

关于java - Android LocationListener 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8302780/

47 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com