我正在使用android融合位置客户端进行后台位置跟踪,即使从内存中清除了该应用程序,该客户端也将继续运行。我为此使用前台服务。除了具有省电模式的Samsung Galaxy设备外,它对于大多数设备都运行完美。我还为应用程序运行时添加了ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS的权限,但三星设备仍然无法完美跟踪。我还使用了地理围栏意图服务以及部分唤醒锁。这个应用程式可以在其他所有装置上正常运作。请检查我用于背景位置的代码。这不是完整的代码。 另外,当我启用位置祝酒功能时,即使在三星上,距离也可以完美追踪。但是,当禁用烤面包片时,则只能在三星中首次使用。
/**********LocationUpdatesService class********/
public class LocationUpdatesService extends Service {
@Override
public void onCreate() {
Log.i(TAG, "Service onCreate");
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
mLocationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
onNewLocation(locationResult.getLastLocation());
}
};
createLocationRequest();
if (checkPermissions()) {
getLastLocation();
}
powerManager = (PowerManager) getSystemService(POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"myapp::MyWakelockTag");
wakeLock.acquire();
}
public void requestLocationUpdates() {
Log.i(TAG, "Requesting location updates");
//Utils.setRequestingLocationUpdates(this, true);
startService(new Intent(getApplicationContext(), LocationUpdatesService.class));
try {
mFusedLocationClient.requestLocationUpdates(mLocationRequest,
mLocationCallback, Looper.myLooper());
} catch (SecurityException unlikely) {
//Utils.setRequestingLocationUpdates(this, false);
Log.e(TAG, "Lost location permission. Could not request updates. " + unlikely);
}
}
public void removeLocationUpdates() {
Log.i(TAG, "Removing location updates");
removeActivityUpdatesButtonHandler();
try {
mFusedLocationClient.removeLocationUpdates(mLocationCallback);
wakeLock.release();
stopForeground(true);
stopSelf();
} catch (SecurityException unlikely) {
//Utils.setRequestingLocationUpdates(this, true);
Log.e(TAG, "Lost location permission. Could not remove updates. " + unlikely);
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "Service started");
boolean startedFromNotification = intent.getBooleanExtra(EXTRA_STARTED_FROM_NOTIFICATION,
false);
// We got here because the user decided to remove location updates from the notification.
if (startedFromNotification) {
//removeLocationUpdates();
//stopSelf();
}
startForeground(NOTIFICATION_ID, getNotification());
// Tells the system to not try to recreate the service after it has been killed.
return START_STICKY;
}
}
我在主要活动中正在使用此绑定服务。 上面只是示例代码,供任何人参考。如果有人知道解决方案,请告诉我。对于带有节电器的三星设备,我只是遇到麻烦。否则,我的服务将无法正常工作并且可以完美地跟踪距离。