我希望在打开对话框后点击位置按钮,检测用户的位置并显示用户的位置然后用户关闭对话框,位置监听器移除而不是从onLocationChanged
获取位置,I尝试在覆盖locationManager.removeUpdate(locListener)
上使用dismiss
但是在再次解雇之后没有任何机会和位置显示!为什么?如何在显示对话框后检测用户的位置,并在检测到位置后,位置监听器删除?感谢
编辑:
public class DialogTest extends Dialog implements android.view.View.OnClickListener {
Context context;
LocationManager locationManager;
LocationListener locationListener;
Location location;
public DialogTest(Context context) {
super(context);
// TODO Auto-generated constructor stub
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.context = context;
setContentView(R.layout.profile_dialog);
getWindow().setBackgroundDrawableResource(R.drawable.background_dialog);
firstAccessLocation=true;
setCancelable(true);
initialize();
}
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
findAddress();
}
private void findAddress() {
// if (gpsCheckBox.isChecked()) {
locationManager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
locationListener = new GPSLocationListener();
locationManager.requestLocationUpdates(locationManager.GPS_PROVIDER, 0,
0, locationListener);
locationManager.requestLocationUpdates(
locationManager.NETWORK_PROVIDER, 0, 0, locationListener);
// }
}
private void stopTracking(){
if(locationManager!=null){
locationManager.removeUpdates(locationListener);
}
}
@Override
public void dismiss() {
// TODO Auto-generated method stub
stopTracking();
gpsTurnOff();
super.dismiss();
}
public class GPSLocationListener implements LocationListener {
@Override
public void onLocationChanged(Location loc) {
// TODO Auto-generated method stub
if(location!=null)
Log.e("location", location.getLatitude()+"");
location = loc;
if (location != null&& firstAccessLocation) {
setAddress(location.getLatitude(), location.getLongitude());
firstAccessLocation=false;
}
Toast.makeText(context, "changed", Toast.LENGTH_LONG).show();
Log.e("location", "changed");
}
@Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
}
答案 0 :(得分:0)
在新代码中,您应该使用LocationClient
而不是LocationManager
。以更高的精度获得最小能量(电池消耗)的位置效率更高。看这里LocationClient vs LocationManager。建立LocationClient
后,您可以致电getLastLocation()
,它会为您提供最后的位置,并且不会启动循环位置更新。
如果您希望坚持LocationManager
使用requestSingleUpdate (String provider, LocationListener listener, Looper looper)
方法,只能从中获取一个最新位置。