mea*_*per 5 java android background geolocation foreground-service
我正在使用 android 融合位置客户端进行后台位置跟踪,即使应用程序从内存中清除,它也会运行。我正在为此使用前台服务。除了具有省电模式的三星 Galaxy 设备外,它在大多数设备上都能完美运行。我还在应用程序运行时添加了 ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS 的权限,但三星设备仍然无法完美跟踪。我还使用地理围栏意图服务和部分唤醒锁。此应用程序在所有其他设备上运行良好。请检查我用于后台位置的代码。这不是完整的代码。此外,当我启用位置吐司时,即使在三星上也能完美跟踪距离。但是当 Toasts 被禁用时,它只能在三星第一次使用。
/**********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;
}
}
Run Code Online (Sandbox Code Playgroud)
我在我的主要活动中使用此绑定服务。以上只是示例代码,供大家参考。如果有人知道解决方案,请告诉我。对于带节电功能的三星设备,我只是遇到了麻烦。否则,我的服务运行良好,可以完美地跟踪距离。
| 归档时间: |
|
| 查看次数: |
1380 次 |
| 最近记录: |