gpt4 book ai didi

安卓 : Remove LocationListener

转载 作者:行者123 更新时间:2023-11-29 14:20:50 26 4
gpt4 key购买 nike

我有以下代码使用 GPS 获取用户位置。(代码工作正常)
但我的问题是,当我关闭程序(按后退按钮)时,它会生成错误消息
应用程序......已停止工作............请重试。 .
我认为我必须删除监听器,因为我在 onDestroy() 中使用了 removeUpdates() 方法,然后也会生成相同的错误消息。
我该如何解决。
我的代码:

public class Location_AddressActivity extends Activity {

/** Called when the activity is first created. */
TextView txt_logitude;
TextView txt_latitude;
TextView txt_address;
LocationListener mlocListener;
LocationManager mlocManager;
Geocoder geocoder;

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txt_logitude=(TextView)findViewById(R.id.txt_logitude);
txt_latitude=(TextView)findViewById(R.id.txt_latitude);
txt_address=(TextView)findViewById(R.id.txt_address);
geocoder = new Geocoder(this, Locale.ENGLISH);
txt_latitude.setText("");
txt_logitude.setText("");
txt_address.setText("");
mlocManager= (LocationManager)getSystemService(Context.LOCATION_SERVICE);
mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
}
public void onDestroy()
{
mlocManager.removeUpdates(mlocListener);
}
class MyLocationListener implements LocationListener
{
public void onLocationChanged(Location location) {
double latitude=location.getLatitude();
double longitude=location.getLongitude();
txt_latitude.setText(new Double(latitude).toString());
txt_logitude.setText(new Double(longitude).toString());
try {
List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
if(addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("Address:\n");
for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
}
txt_address.setText(strReturnedAddress.toString());
}
else{
txt_address.setText("No Address returned!");
}
}
catch (IOException e) {
e.printStackTrace();
txt_address.setText(e.getMessage());
}
}
public void onProviderDisabled(String provider) {
txt_address.setText("GPS Disable");
}
public void onProviderEnabled(String provider) {
txt_address.setText("GPS Enable");
}
}
}

谢谢..

最佳答案

您已在您的 Activity 的 onDestroy() 中删除了对 super.onDestroy 的调用。只需按如下所示更改该代码并试一试。

public  void onDestroy()
{
super.onDestroy();
mlocManager.removeUpdates(mlocListener);
}

我希望 removeUpdates() 不会给您带来任何问题。

关于安卓 : Remove LocationListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14275053/

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