#StackBounty: #java #android #service [Edited]onTaskRemoved not getting called if the activity started by the service is removed

Bounty: 50

I am using oreo 8.1.0.
I am facing a weird problem whose solution I can’t find on stackoverflow, hence I am writing this question. I know one solution that through foreground service, I can implement it but I don’t find notification user friendly in my application context.

I will describe my problem using two cases.

Case 1:
When user opens my app by clicking on the icon and removes it from recent apps, then service automatically restarts. This is fine.

Case 2:
Here my app is closed and is not in recent apps.
When user copies a text, then my service starts one of the activity of my app but when he removes it from the recent apps, then my service gets stopped permanently.

So my problem lies in second case,I don’t want my service to get killed. Even if it gets killed I want it to restart.

I tried all the methods mentioned on the stackoverflow like using START_STICKY and onTaskRemoved but I am not able to make it work.

Even I tried killing my activity whenever user clicks on on recent app button and remove it from the recent apps programmatically but this also did not work.
Though this restarts the service even in second case when user kills my app using the back button.

This part of the code is from the activity which opens when user copies some text.

public void finish() {
    } else {


This part of the code is from the service that starts the activity.

public void onTaskRemoved(Intent rootIntent){
    Log.d("testing 12","onTaskRemoved");
    Intent restartServiceTask = new Intent(getApplicationContext(),CBWatcherService.class);
    PendingIntent restartPendingIntent =PendingIntent.getService(getApplicationContext(), 1,restartServiceTask, PendingIntent.FLAG_ONE_SHOT);
    AlarmManager myAlarmService = (AlarmManager) getApplicationContext().getSystemService(this.ALARM_SERVICE);
            SystemClock.elapsedRealtime() + 1000,


public int onStartCommand(Intent intent,int flag,int startId){
    super.onStartCommand(intent, flag, startId);
    return START_STICKY;


I just need the service to remain alive.Here are the things that will not hinder the user experience in my app case
1. Killing the activity by yourself programitically when onPause is called so that service does not get killed is acceptable if you make it happen
2. Showing the notification for few second is acceptable
3. Restarting the service is acceptable

Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.