我的应用场景是我想跟踪员工的位置。我有一个广播接收器,它侦听设备引导广播并注册一个警报管理器。当警报管理器滴答时,它会注册两个位置监听器,一个监听gps和其他网络。我希望当我在onLocationChange()方法中获得第一个位置更新时,保存位置并取消注册该位置侦听器,以便当警报管理器再次打勾时,它不会重复。要取消注册,我将位置侦听器作为静态对象在onLocationChange()中访问它们。但我发现它不是删除位置侦听器。这里是我的代码示例:LocationManager.removeUpdates(侦听器)不删除位置侦听器
public class BootTimeServiceActivator extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Calendar calendar = Calendar.getInstance();
AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent mIntent = new Intent(context, MyBroadCastReceiver.class);
PendingIntent mPendingIntent = PendingIntent.getBroadcast(context, 0, mIntent, PendingIntent.FLAG_CANCEL_CURRENT);
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 20 * 60 * 1000, mPendingIntent);
}
}
//..........
public class MyBroadCastReceiver extends BroadcastReceiver{
public static LocationManager locationManager;
public static MyLocationListener networkLocationListener;
public static MyLocationListener gpsLocationListener;
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Toast.makeText(context, "Alarm has been called...", Toast.LENGTH_SHORT).show();
initLocationListeners(context);
registerLocationListeners();
}
public void initLocationListeners(Context context) {
locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
networkLocationListener = new MyLocationListener(context);
gpsLocationListener = new MyLocationListener(context);
}
public void registerLocationListeners() {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 100, 0, gpsLocationListener);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 100, 0, gpsLocationListener);
}
}
\\.....
public class MyLocationListener implements LocationListener {
Context context;
public MyLocationListener(Context context) {
this.context = context;
}
@Override
public void onLocationChanged(Location location) {
if(location != null) {
SDCardService sdService = new SDCardService(context);
try {
sdService.logToDB(location);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("provider",location.getProvider());
if(location.getProvider().equals(LocationManager.GPS_PROVIDER)) {
MyBroadCastReceiver.locationManager.removeUpdates(MyBroadCastReceiver.gpsLocationListener);
}
else if(location.getProvider().equals(LocationManager.NETWORK_PROVIDER)) {
MyBroadCastReceiver.locationManager.removeUpdates(MyBroadCastReceiver.networkLocationListener);
}
}
}
任何人都可以引导我,我错了吗?
那么什么是你做的修改?就好像你删除了你的网络监听器你不会得到网络更新。 – amandroid
是的,因为我只想获得单个位置更新。 –