Как сделать так, чтобы GPS-сервис переднего плана не останавливался при выключенном экране телефона? - PullRequest
0 голосов
/ 19 октября 2019

Я пытаюсь создать службу переднего плана, которая будет отслеживать путь пользователя

Я хочу, чтобы этот сервер работал и отслеживал местоположение пользователя, пока пользователь не закрылся, но теперь он работает нормально с отслеживанием местоположения и путем, ноЕдинственная проблема заключается в том, что когда я обслуживаю телефон и кладу его в карман, то через некоторое время услуга разрушается. но я положил его на стол, затем служба работает всю ночь

Вот код запуска java startForegroundService(new Intent(this, GoogleService.class));

Вот код таймера, который запускается при запуске службы

        mTimer.schedule(new TimerTaskToGetLocation(), 10,1000 );```

in TimerTasktoGetLocation 
```java                         sendNotification_pause(getString(R.string.app_name)+" mp service",utils.convertSecondsToHMmSs(total_time),distance);

Этот код для отображения уведомлений

RemoteViews notificationLayout = null;

        notificationLayout= new RemoteViews(getPackageName(), R.layout.custom_notification_location);


        Intent intent = new Intent(getApplicationContext(), GoogleService.class);
        PendingIntent pendIntentapp_oopen = PendingIntent.getActivity(this, 0, new Intent(context, DrawerActivity.class).setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT), 0);
        PendingIntent pending_intent_end = PendingIntent.getService(this, 0, intent.setAction(Actions.SERVICE_STOP), 0);

       notificationLayout.setTextViewText(R.id.custom_notification_distance, "Distanz: "+Utils.distance_with_unite(distance));
        notificationLayout.setTextViewText(R.id.custom_notification_duration, "Dauer: "+duration);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "CANNEL01")
                .setSmallIcon(R.drawable.login_logo)
                .setAutoCancel(false)
                .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                .setPriority(NotificationManager.IMPORTANCE_HIGH)
                .setStyle(new NotificationCompat.DecoratedCustomViewStyle())
                .setCustomContentView(notificationLayout)
                .setOnlyAlertOnce(true)
                .addAction(new NotificationCompat.Action(R.drawable.ic_close_black_24dp,"End",pending_intent_end))
                .setContentIntent(pendIntentapp_oopen);


        builder.setOngoing(true);


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

            int importance = NotificationManager.IMPORTANCE_HIGH;
            @SuppressLint("WrongConstant") NotificationChannel channel = new NotificationChannel("CANNEL01", "Location", importance);
            channel.setDescription("All the different interval tones");
            // Register the channel with the system; you can't change the importance
            // or other notification behaviors after this
            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
            startForeground(101,builder.build());


        }else {
            startForeground(101,builder.build());

            NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
        }

Я хочу, чтобы этот сервер запускался и отслеживал местоположение пользователя, пока пользователь не закрылся, но теперь он отлично работает с отслеживанием местоположения и путем, но толькопроблема в том, что когда я обслуживаю и кладу телефон в карман, то через некоторое время услуга разрушается. Еще одна вещь, когда я держу это на столе, тогда служба работает всю ночь. Мне интересно, как, почему это происходит

для примера https://play.google.com/store/apps/details?id=com.runtastic.android&hl=en это приложение не запрашивает никакого специального разрешения и отслеживает путь, это будет также хорошо, я получаю подсказку, как этот видсервис работает?

...