我已经设置了一个由 BroadcastReceiver 接收的警报,它启动了一个 WakefulIntentService (类LocationMonitor
)。在LocationMonitor
我有:
private static final int MIN_TIME_BETWEEN_SCANS = 1 * 30 * 1000;
private static final int MIN_DISTANCE = 0;
@Override
protected void doWakefulWork(Intent intent) {
final CharSequence action = intent.getAction();
if (action == null) { // monitor command from the alarm manager
// the call below enables the LocationReceiver
BaseReceiver.enable(this, ENABLE, LocationReceiver.class);
if (lm == null) lm = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
Intent i = new Intent(this, LocationReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(this, NOT_USED, i,
PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_CANCEL_CURRENT);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,
MIN_TIME_BETWEEN_SCANS, MIN_DISTANCE, pi);
} else if (ac_location_data.equals(action)) {
final Bundle extras = intent.getExtras();
if (extras != null) {
final Location loc = (Location) extras
.get(LocationManager.KEY_LOCATION_CHANGED);
if (loc == null) {
w("NULL LOCATION - EXTRAS : " + extras); //Log.w
// while gps is disabled I keep getting this :
// NULL LOCATION - EXTRAS : Bundle[{providerEnabled=false}]
} else {
final double lon = loc.getLongitude();
final double lat = loc.getLatitude();
w("latitude :" + lat + " -- longitude : " + lon);
}
}
}
}
我对上面的代码有几个问题。
- 如果 GPS最初被禁用,然后我启用它,我会得到一堆
W/GpsLocationProvider(...): Unneeded remove listener for uid 1000
. 警告来自这里。我在代码中找不到触发侦听器的删除,也看不到它们在哪里被分配了 uid 1000(显然是系统服务器)。 当我启用 gps 时,我得到了预期的位置,然后是“RemoteException”
LocationManagerService(...): RemoteException 在接收器上调用 onLocationChanged{4083ee68 Intent PendingIntent{4084e6b8: PendingIntentRecord{4083ef78 gr.uoa.di.monitoring.android broadcastIntent}}}mUpdateRecords: {gps=UpdateRecord{40838180 mProvider: gps mUid: 10064} }
这不是一个真正的 RemoteException,只是一个 PendingIntent.CancelledException - 该消息非常具有误导性。或者我认为:它来自这里调用这个。我的问题是:为什么要重用 Intent - FLAG_ONE_SHOT 不应该处理它吗?
但最重要的问题是:当我像这样注册 PendingIntent 时,我希望收到什么意图?我应该使用什么标志?
请记住,我正在使用这种模式,因为我想让手机即使在睡着的时候也能更新它的位置,这实现了它(我确实得到了位置更新)。我尝试requestSingleUpdate
使用FLAG_ONE_SHOT
.
接收者 :
public final class LocationReceiver extends BaseReceiver {
private static final Class<? extends Monitor> MONITOR_CLASS =
LocationMonitor.class;
@Override
public void onReceive(Context context, Intent intent) {
d(intent.toString());
final String action = intent.getAction();
d(action + "");
final Intent i = new Intent(context, MONITOR_CLASS);
i.fillIn(intent, 0); // TODO do I need flags ?
i.setAction(ac_location_data.toString());
WakefulIntentService.sendWakefulWork(context, i);
}
}