Я разрабатываю приложение для водителей такси, которое сообщает диспетчерскому веб-приложению о местонахождении автомобиля. Мне удалось надежно получить местоположение устройства с помощью FusedLocationProviderClient и обновлений местоположения, которые отправляются через службу Foreground. К сожалению, мой планшет (Huawei MediaPad T5 - Android Oreo 8.0) активно убивает службу, пока приложение не находится на переднем плане. Согласно документации Android, я делаю это правильно (если нет, пожалуйста, поправьте меня).
Я прилагаю исходный код сервиса ниже:
import android.Manifest;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationCompat;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import driver.taxis.dcsoft.cz.R;
import driver.taxis.dcsoft.cz.communication.CommunicatorManager;
import driver.taxis.dcsoft.cz.gui.activities.MainActivity;
import driver.taxis.dcsoft.cz.preferences.PreferencesConstants;
import driver.taxis.dcsoft.cz.preferences.PreferencesManager;
public class UpdateLocationService extends Service {
private static final String TAG = "LocationService";
private FusedLocationProviderClient mFusedLocationClient;
private final static long UPDATE_INTERVAL = 15 * 1000; /* 4 secs */
private final static long FASTEST_INTERVAL = 7 * 1000; /* 2 sec */
private LocationCallback locationCallback;
@Override
public void onCreate() {
super.onCreate();
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
if (Build.VERSION.SDK_INT >= 26) {
String CHANNEL_ID = "my_channel_01";
NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
"My Channel",
NotificationManager.IMPORTANCE_DEFAULT);
((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(channel);
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setOngoing(true)
.setContentTitle("Aplikace " + MainActivity.getContext().getString(R.string.app_name) + " odesílá polohu na pozadí.")
.setContentIntent(pendingIntent)
.build();
startForeground(1, notification);
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand: called.");
getLocation();
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
if(locationCallback != null) {
mFusedLocationClient.removeLocationUpdates(locationCallback);
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
private void getLocation() {
// Create the location request to start receiving updates
LocationRequest mLocationRequestHighAccuracy = new LocationRequest();
mLocationRequestHighAccuracy.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequestHighAccuracy.setInterval(UPDATE_INTERVAL);
mLocationRequestHighAccuracy.setFastestInterval(FASTEST_INTERVAL);
// new Google API SDK v11 uses getFusedLocationProviderClient(this)
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "getLocation: stopping the location service.");
stopSelf();
return;
}
Log.d(TAG, "getLocation: getting location information.");
locationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
Log.d(TAG, "onLocationResult: got location result.");
Location location = locationResult.getLastLocation();
if (location != null) {
String vehicleId = PreferencesManager.loadStringPreference(PreferencesConstants.SPZ_STRING, "");
if(vehicleId.isEmpty() || vehicleId == null) {
return;
}
CommunicatorManager.INSTANCE.sendPositionRequest(location);
}
}
};
mFusedLocationClient.requestLocationUpdates(mLocationRequestHighAccuracy, locationCallback,
Looper.myLooper()); // Looper.myLooper tells this to repeat forever until thread is destroyed
}
}
Подробнее здесь: https://stackoverflow.com/questions/693 ... foreground
Служба определения местоположения отключается, когда она не на переднем плане ⇐ Android
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение