Отказ от обслуживания, остановка через несколько минут или блокировка телефона - PullRequest
0 голосов
/ 25 сентября 2018

Я пытаюсь создать службу переднего плана, которая передает сообщение каждые 20 секунд, но эта служба останавливается через несколько минут или блокирует телефон.Я тестирую этот сервис в Android 8 (O).мой код:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
  input = intent.getStringExtra("inputExtra");

  new Thread(new Runnable() {
    public void run() {
      while (progressStatus < 10000000) {
        progressStatus += 1;           
        handler.post(new Runnable() {
          @SuppressLint("MissingPermission")
          public void run() {
            Intent notificationIntent = new Intent(ExampleService.this, MainActivity.class);
            PendingIntent pendingIntent = PendingIntent.getActivity(ExampleService.this,
              0, notificationIntent, 0);
            String mmm = CHANNEL_ID;

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
              notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
              id = "id_product";
              // The user-visible name of the channel.
              CharSequence name = "Product";
              // The user-visible description of the channel.
              String description = "Notifications regarding our products";
              int importance = NotificationManager.IMPORTANCE_MAX;
              NotificationChannel mChannel = new NotificationChannel(id, name, NotificationManager.IMPORTANCE_DEFAULT);
              // Configure the notification channel.
              mChannel.setDescription(description);
              mChannel.enableLights(true);
              // Sets the notification light color for notifications posted to this
              // channel, if the device supports this feature.
              mChannel.setLightColor(Color.RED);
              notificationManager.createNotificationChannel(mChannel);
            }

            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getApplicationContext(),"id_product")
              .setContentTitle("Example Service")
              .setContentText(input)
              .setSmallIcon(R.drawable.ic_launcher_background)
              .setContentIntent(pendingIntent)
              .setChannelId(id)

              .setAutoCancel(true).setContentIntent(pendingIntent)
              .setNumber(1)
              .setColor(255)
              .setContentText(input)
              .setWhen(System.currentTimeMillis());
            notificationManager.notify(1, notificationBuilder.build());

            Notification notification = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID)
              .setContentTitle("Example Service")
              .setContentText(input)
              .setSmallIcon(R.drawable.ic_launcher_background)
              .setContentIntent(pendingIntent)
              .build();

              Toast.makeText(getApplicationContext(), " run service" , Toast.LENGTH_SHORT).show();

              startForeground(1, notification);
            }
        });
        try {
          Thread.sleep(20000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    }
  }).start();

  return START_STICKY;
}

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

эта служба в порядке в начале и в первые минуты, но обычно она заканчивается через несколько минут и иногда запускается снова через несколько минут.Иногда он запускается при подключении к Интернету, иногда он начинает работать при подключении USB-кабеля.Я действительно не знаю, в чем причина.Есть ли кто-нибудь, кто может помочь мне в этом?

1 Ответ

0 голосов
/ 25 сентября 2018

Пожалуйста, внимательно прочитайте документацию по Android Oreo 8.0 где-нибудь в здесь , для фоновых сервисов

Я предлагаю использовать:

  1. JobScheduler

  2. Workmanager

Надеюсь, этот ответ поможет вам в вашем текущем коде

https://stackoverflow.com/a/48302378/6541643

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