我正在使用 FusedLocationProviderClient 开发位置跟踪应用程序。我有一个后台服务,每 5 分钟跟踪一次电话的位置。
一切都很好,但是一旦手机空闲3到4个小时后,后台服务就会停止定位。当用户解锁手机时,跟踪再次开始。
有人可以指导我可能导致问题的原因吗?
位置更新广播接收器
public class LocationUpdatesBroadcastReceiver extends BroadcastReceiver {
public static final String TAG = "LUBroadcastReceiver";
public static final String ACTION_PROCESS_UPDATES =
"com.orangeapp.discountnotifier.receiver.action" +
".PROCESS_UPDATES";
@Override
public void onReceive(Context context, Intent intent) {
if (intent != null) {
final String action = intent.getAction();
if (ACTION_PROCESS_UPDATES.equals(action)) {
LocationResult result = LocationResult.extractResult(intent);
if (result != null) {
List<Location> locations = result.getLocations();
Utils.setLocationUpdatesResult(context, locations);
// Utils.checKOffersByLatLng(context, locations);
Utils.sendNotification(context, Utils.getLocationResultTitle(context, locations));
Log.e(TAG, Utils.getLocationUpdatesResult(context));
}
}
}
}
}
主要活动
private PendingIntent getPendingIntent() {
// Note: for apps targeting API level 25 ("Nougat") or lower, either
// PendingIntent.getService() or PendingIntent.getBroadcast() may be used when requesting
// location updates. For apps targeting API level O, only
// PendingIntent.getBroadcast() should be used. This is due to the limits placed on services
// started in the background in "O".
// TODO(developer): uncomment to use PendingIntent.getService().
// Intent intent = new Intent(this, LocationUpdatesIntentService.class);
// intent.setAction(LocationUpdatesIntentService.ACTION_PROCESS_UPDATES);
// return PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Intent intent = new Intent(this, LocationUpdatesBroadcastReceiver.class);
intent.setAction(LocationUpdatesBroadcastReceiver.ACTION_PROCESS_UPDATES);
return PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
protected void startLocationUpdates() {
try {
Log.i(TAG, "Starting location updates");
Utils.setRequestingLocationUpdates(this, true);
mFusedLocationClient.requestLocationUpdates(mLocationRequest, getPendingIntent());
} catch (Exception e) {
Utils.setRequestingLocationUpdates(this, false);
e.printStackTrace();
}
}