API провайдера Fused Location прекращает отправку обновления местоположения через несколько часов - PullRequest
1 голос
/ 04 июля 2019

Попытка получать обновление местоположения каждые 5 минут для отслеживания местоположения пользователей.

Попытка установки приоритета как PRIORITY_HIGH_ACCURACY, удаление setExpirationDuration и использование службы Foreground

Класс обслуживания местоположения

public class ForegroundLocationService extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {

    public static final String EXTRA_LATITUDE = "extra_latitude";
    public static final String ACTION_LOCATION_BROADCAST = ForegroundLocationService.class.getName() + "LocationBroadcast";
    public static final String EXTRA_LONGITUDE = "extra_longitude";
    private static final String TAG = ForegroundLocationService.class.getSimpleName();
    public static final int GPS_NOTIFICATION = 1;
    private static final int UPDATE_INTERVAL_IN_SECONDS = 60*5;
    private static final int LOCATION_INTERVAL = 5*60*1000;
    private static final int FASTEST_LOCATION_INTERVAL = 3*60*1000;

    private boolean isForeground = false;
    private GoogleApiClient googleApiClient;
    private PowerManager.WakeLock wakeLock;

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

        googleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        final PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
        wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (!isForeground) {
            Log.v(TAG, "Starting the " + this.getClass().getSimpleName());
            startForeground(ForegroundLocationService.GPS_NOTIFICATION,
                    notifyUserThatLocationServiceStarted());
            isForeground = true;
            googleApiClient.connect();
            wakeLock.acquire();
        }
        return START_STICKY;
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        Intent restartService = new Intent(getApplicationContext(),
                this.getClass());
        restartService.setPackage(getPackageName());
        PendingIntent restartServicePI = PendingIntent.getService(
                getApplicationContext(), 1, restartService,
                PendingIntent.FLAG_ONE_SHOT);
        AlarmManager alarmService = (AlarmManager)getApplicationContext().getSystemService(Context.ALARM_SERVICE);
        alarmService.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() +1000, restartServicePI);
    }

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

    @Override
    public void onDestroy() {
        Log.v(TAG, "Stopping the " + this.getClass().getSimpleName());
        stopForeground(true);
        isForeground = false;
        googleApiClient.disconnect();
        if (null != wakeLock && wakeLock.isHeld()) {
            wakeLock.release();
        }
        super.onDestroy();
    }

    private LocationRequest getLocationRequest() {
        LocationRequest locationRequest = LocationRequest.create();
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        locationRequest.setInterval(LOCATION_INTERVAL);
        locationRequest.setFastestInterval(FASTEST_LOCATION_INTERVAL);
        locationRequest.setMaxWaitTime(TimeUnit.SECONDS.toMillis(UPDATE_INTERVAL_IN_SECONDS));
        return locationRequest;
    }

    private Notification notifyUserThatLocationServiceStarted() {
        Intent notificationIntent = new Intent(this, SalesHome.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
                notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);
        Notification.Builder builder;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            String NOTIFICATION_CHANNEL_ID = "com.healingpharma.sales_touch";
            String channelName = "My Background Service";
            NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
            chan.setLightColor(Color.BLUE);
            chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
            NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            assert manager != null;
            manager.createNotificationChannel(chan);
            builder = new Notification.Builder(this,NOTIFICATION_CHANNEL_ID)
                    .setSmallIcon(R.mipmap.small_icon)
                    .setContentTitle("Healing Pharma")
                    .setContentText("Location tracking")
                    .setContentIntent(pendingIntent)
                    .setWhen(System.currentTimeMillis());
        } else {
            builder = new Notification.Builder(this)
                    .setSmallIcon(R.mipmap.small_icon)
                    .setContentTitle("Healing Pharma")
                    .setContentText("Location tracking")
                    .setContentIntent(pendingIntent)
                    .setWhen(System.currentTimeMillis());
        }
        final Notification notification;
        notification = builder.build();
        return notification;
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        try {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, getLocationRequest(), this);
        } catch (SecurityException securityException) {
            Log.e(TAG, "Exception while requesting location updates", securityException);
        }
    }

    @Override
    public void onConnectionSuspended(int i) {
        Log.i(TAG, "Google API Client suspended.");
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        Log.e(TAG, "Failed to connect to Google API Client.");
    }

    @Override
    public void onLocationChanged(Location location) {
        if (location != null) {
            Log.d(TAG, "== location != null");
            float acc = location.getAccuracy();
            // writing log with current time in txt file in external storage of the device.
            com.healingpharma.sales_touch.Constants.appendLog("Latitude : " + String.valueOf(location.getLatitude())+" Longitude : "+ String.valueOf(location.getLongitude()));
           
        if (acc <= 200) {
                sendMessageToUI(String.valueOf(location.getLatitude()), String.valueOf(location.getLongitude()));
            }
        }
    }

    private void sendMessageToUI(String lat, String lng) {
        Log.d(TAG, "Sending info...");
        Intent intent = new Intent(ACTION_LOCATION_BROADCAST);
        intent.putExtra(EXTRA_LATITUDE, lat);
        intent.putExtra(EXTRA_LONGITUDE, lng);
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    }
}

Ниже кода для запроса службы обновления местоположения из действия

Intent intent = new Intent(this, ForegroundLocationService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        this.getApplication().startForegroundService(intent);
} else {
       this.getApplication().startService(intent);
}

Я регистрирую обновление местоположения в txt-файле на устройстве, но через несколько часов оно прекращает отправку местоположения.

Что не так я делаю в своем коде или любом решении?

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