Forgeround service stop after a few minutes or locking the phone
Asked Answered
G

1

6

I try to create foreground service that toast a message every 20 second but this service stop after a few minutes or locking the phone. I test this service in android 8 (O). my code is :

@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;
}

this service is ok at the start and first minutes but But it usually ends after a few minutes and sometimes starts again after a few minutes. Sometimes it starts up by connecting to the Internet, sometimes it starts to work by connecting the USB cable. I really do not know what the cause is. IS there someone who can help me on this?

Gelatinize answered 25/9, 2018 at 3:56 Comment(1)
I must say that the service is always running in the running service of my device.Gelatinize
M
2

Please read the Android Oreo 8.0 Documentation properly somewhere in here, for Background services

My Suggestion is to Use:

  1. JobScheduler

  2. Workmanager

Hope this Answer may help you in Your current code

https://mcmap.net/q/260436/-background-service-for-android-oreo

Marguerita answered 25/9, 2018 at 4:6 Comment(7)
I create channel for notification and i check the android version all the recommended part of your link is in my cod but after a few minutes notification does not close and toast does not repeat.Gelatinize
service is always running in the running service of my device . It's really cool to start working as soon as the USB cable is connected.Gelatinize
Because api level more than 21 the background services killed by the OSMarguerita
when i click on notification service start working aganGelatinize
what should i do to stop killing service by OS?Gelatinize
use JobSchedulerMarguerita
schedule it according to your needMarguerita

© 2022 - 2024 — McMap. All rights reserved.