2

My Solution to write sticky service is working fine below Android version Lollipop but above Lollipop version service is getting closed when user kills the application from background.

Any suggestion guys.

ankuranurag2
  • 2,300
  • 15
  • 30

3 Answers3

2

Use can start service as Foreground even os can't kill it for more info check linkRunning a service in the foreground

Omar Hayat
  • 378
  • 2
  • 12
  • But in case of foreground service we have to show service notification, that I don't want – Kanhaiya Chaurasiya Oct 03 '17 at 05:56
  • You can hide that notification I am using it like this Notification notification = new NotificationCompat.Builder(service).build(); service.startForeground(NOTIFICATION_ID, notification); – Omar Hayat Oct 03 '17 at 05:59
  • try this method just pass it service name which you want to run as foreground private static void startForeground(Service service) { Notification notification = new NotificationCompat.Builder(service).build(); service.startForeground(NOTIFICATION_ID, notification); } – Omar Hayat Oct 03 '17 at 06:03
  • like you can hide notification startForeground(Yourservice.instance); startForeground(this); //Cancel this service's notification, resulting in zero notifications stopForeground(true); – Omar Hayat Oct 03 '17 at 06:07
1

I got solution about it not why it's work for me but try this.

Override the onTaskRemoved()

 @Override
    public void onTaskRemoved(Intent rootIntent) {
        // TODO Auto-generated method stub

        //Write your stuff which you set in onDestroy()
    }

and set same code which you set in onDestroy() it work for me.

Yash ajabiya
  • 134
  • 2
  • 8
0

For instance below code will work on Lollipop.

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

But Things are getting quite tricky Since android N release. And now android O put some more restrictions on background tasks. So the thing in In Android O no background service can run the service will kill by OS just after your application gone from the foreground(Only Foreground services can run i.e Service with a notification on top). Here is a informative solution.

ADM
  • 20,406
  • 11
  • 52
  • 83