我的问题是我可以在后台获取位置,但是一旦应用程序被杀死,它就会停止更新。一旦从 getlastlocation 方法获取纬度和经度,我就会将其存储到 firebase 中。前台和后台模式更新正常。但是当我像清除所有后台应用程序一样关闭时,它就会停止更新。
public class MyBackgroundLocationService extends Service {
private static final String TAG = MyBackgroundLocationService.class.getSimpleName();
private FusedLocationProviderClient mLocationClient;
private LocationCallback mLocationCallback;
public MyBackgroundLocationService() {
}
@Override
public void onCreate() {
super.onCreate();
mLocationClient = LocationServices.getFusedLocationProviderClient(getApplicationContext());
mLocationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
if (locationResult == null) {
Log.d(TAG, "onLocationResult: location error");
return;
}
List<Location> locations = locationResult.getLocations();
LocationResultHelper helper = new LocationResultHelper(getApplicationContext(), locations);
helper.showNotification();
helper.saveLocationResults();
Toast.makeText(getApplicationContext(), "Location received: " + locations.size(), Toast.LENGTH_SHORT).show();
}
};
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand: called");
startForeground(1001, getNotification());
getLocationUpdates();
return START_STICKY;
}
private Notification getNotification() {
NotificationCompat.Builder notificationBuilder = null;
notificationBuilder = new NotificationCompat.Builder(getApplicationContext(),
App.CHANNEL_ID)
.setContentTitle("Location Notification")
.setContentText("Location service is running in the background.")
.setSmallIcon(R.mipmap.ic_launcher)
.setAutoCancel(true);
return notificationBuilder.build();
}
private void getLocationUpdates() {
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(5000);
locationRequest.setFastestInterval(4000);
locationRequest.setMaxWaitTime(15 * 1000);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
stopSelf();
return;
}
mLocationClient.requestLocationUpdates(locationRequest, mLocationCallback, Looper.myLooper());
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: called");
stopForeground(true);
mLocationClient.removeLocationUpdates(mLocationCallback);
}
}
所以我使用前台服务在后台更新位置,它会在通知中显示这些更新。一旦应用程序被杀死,通知也消失了。请请任何人帮助我。
如果您需要更清楚的问题,我会解释。请有人理解我的痛苦