Я хочу создать приложение для отслеживания местоположения для Android, которое может сохранять координаты пользователя каждую минуту в фоновом режиме. Наше приложение отлично работает на устройствах с автономными картами Google, но на устройствах, где у нас нет автономных карт и подключения к Интернету, тогда оно перестает получать обновления местоположения.
при попытке доступа к широте и долготе с помощью двух подходов Google Fused API и LocationManager имеют одну и ту же проблему, ниже приведен мой код;
public class BackgroundLocationService extends Service {
@Override
public void onCreate() {
super.onCreate();
initData();
}
//Location Callback
private LocationCallback locationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
Location currentLocation = locationResult.getLastLocation();
lat= Double.toString(currentLocation.getLatitude());
longit=Double.toString(currentLocation.getLongitude());
}
};
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
prepareForegroundNotification("");
startLocationUpdates();
return START_STICKY;
}
@SuppressLint("MissingPermission")
private void startLocationUpdates() {
mFusedLocationClient.requestLocationUpdates(this.locationRequest,
this.locationCallback, Looper.myLooper());
}
private void prepareForegroundNotification(String msg) {
if(msg.length()==0)
{
msg="HCM Location Tracking";
}
else {
msg="HCM, "+msg;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel serviceChannel = new NotificationChannel(
"1",
msg,
NotificationManager.IMPORTANCE_HIGH
);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(serviceChannel);
}
Intent notificationIntent = new Intent(this, SplashActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
121,
notificationIntent, PendingIntent.FLAG_IMMUTABLE);
Notification notification = new NotificationCompat.Builder(this, "1")
.setContentTitle(getString(R.string.app_name))
.setContentTitle(msg)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pendingIntent)
.build();
startForeground(1, notification);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
private void initData() {
locationRequest = new LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, UPDATE_INTERVAL_IN_MILLISECONDS)
.setWaitForAccurateLocation(false)
.setMinUpdateIntervalMillis(UPDATE_INTERVAL_IN_MILLISECONDS)
.setMaxUpdateDelayMillis(UPDATE_INTERVAL_IN_MILLISECONDS)
.build();
mFusedLocationClient =
LocationServices.getFusedLocationProviderClient(Global.getInstance());
gpsTracker = new GPSTracker( this);
getCoordinatesFromMangerHandler();
locationSettings();
}
private void getCoordinatesFromMangerHandler() {
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
getCoordinatesFromManger();
mHandler.postDelayed(this, CHECK_INTERVAL);
}
}, CHECK_INTERVAL);
}
private void getCoordinatesFromManger() {
if(gpsTracker==null){
gpsTracker = new GPSTracker( this);
}
gpsTracker.getLocation();
lat= Double.toString(gpsTracker.getLatitude());
longit=Double.toString(gpsTracker.getLongitude());
}
private void locationSettings() {
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
SettingsClient client = LocationServices.getSettingsClient(this);
Task task = client.checkLocationSettings(builder.build());
task.addOnSuccessListener(new OnSuccessListener() {
@Override
public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
}
});
task.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
if (e instanceof ResolvableApiException) {
try {
ResolvableApiException resolvable = (ResolvableApiException) e;
prepareForegroundNotification("Kindly enable Wi-Fi scanning and location.");
} catch (Exception sendEx) {
}
}
}
});
}
@Override
public void onDestroy() {
super.onDestroy()
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("restartservice");
broadcastIntent.setClass(this, RestartUserActivity.class);
this.sendBroadcast(broadcastIntent);
}
}
Подробнее здесь: https://stackoverflow.com/questions/782 ... on-android