Мне нужен хороший пример обновления местоположения из фона - PullRequest
0 голосов
/ 13 апреля 2020

Привет, я новичок в разработке android. Я занимаюсь разработкой приложения, которое нуждается в постоянном обновлении местоположения, даже если оно работает в фоновом режиме. Я нацеливаюсь android p ie. Я искал и создал службу для обновлений местоположения, но android через некоторое время убивает эту службу и приложение. Когда эта служба убита, мое приложение также уничтожается, поэтому оно также перестает слушать уведомления FCM. Вот что я попробовал.

publi c Класс LocationService расширяет службу {

private final static String TAG = "LocationService";
public final static String serviceIntent = "MyLocationService";

private final LocationServiceBinder binder = new LocationServiceBinder();

private final static String CHANNEL_ID = "Alteemar Location Service";
private FusedLocationProviderClient fusedLocationProviderClient;
private final static long UPDATE_INTERVAL = 4*1000;  //4 sec
private final static long FASTEST_INTERVAL = 2*1000;
private LoginStatus user;

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

public class LocationServiceBinder extends Binder{
    public LocationService getService(){
        return LocationService.this;
    }
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    getLocation();

    return START_STICKY;
}

@Override
public void onCreate() {
    super.onCreate();

    user = SharedPref.getSharedPreferences(getApplicationContext());
    fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);

    if(Build.VERSION.SDK_INT > 26){
        CharSequence name = "Alteemar";
        String description = "Incoming Alteemar Push Notifications.";
        NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, NotificationManager.IMPORTANCE_DEFAULT);
        channel.setDescription(description);
        // Register the channel with the system; you can't change the importance
        // or other notification behaviors after this
        NotificationManager notificationManager = getSystemService(NotificationManager.class);
        if(notificationManager != null)
            notificationManager.createNotificationChannel(channel);

        Notification notification = new NotificationCompat.Builder(this,CHANNEL_ID)
                .setContentTitle("")
                .setContentText("").build();

        startForeground(1,notification);
    }
}

private void getLocation()
{
    //Create location request
    LocationRequest locationRequest = new LocationRequest();
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    locationRequest.setInterval(UPDATE_INTERVAL);
    locationRequest.setFastestInterval(FASTEST_INTERVAL);

    //Check Internet
    if(!Utils.isNetworkAvailable(this)){
        setNullLocation();
        return;
    }

    //Location Permission
    if(ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
        setNullLocation();
        return;
    }
    fusedLocationProviderClient.requestLocationUpdates(locationRequest,new LocationCallback(){
        @Override
        public void onLocationResult(LocationResult locationResult) {

            Location location = locationResult.getLastLocation();
            if(!Utils.isNetworkAvailable(LocationService.this)){
                setNullLocation();
                return;
            }
            if(!CheckGPS.locationEnabled(LocationService.this)){
                setNullLocation();
                return;
            }
            if(!SharedPref.getStaffStatus(getApplicationContext())){
                setNullLocation();
                return;
            }
            if(location != null){
                LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
                updateUserLocation(latLng);
            }
            //updateUserLocation(latLng);
        }

        @Override
        public void onLocationAvailability(LocationAvailability locationAvailability) {
            if(!locationAvailability.isLocationAvailable())
            {
                setNullLocation();
            }
        }
    }, Looper.myLooper());
}
@Override
public void onDestroy() {
    super.onDestroy();
    Intent restartService = new Intent(RESTART_SERVICE);
    sendBroadcast(restartService);
}

@Override
public void onTaskRemoved(Intent rootIntent) {
    super.onTaskRemoved(rootIntent);
    Intent restartService = new Intent(RESTART_SERVICE);

    sendBroadcast(restartService);
}

}

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...