1

I hope title itself says what's my question is.

I have a Service which runs in foreground.

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    NotificationCompat.Builder builder = new NotificationCompat.Builder(
            this);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
            new Intent(this, WidgetFlashReceiver.class)
                    .setAction(Constants.ACTION_NOTIFICATION_CLICK),
            PendingIntent.FLAG_CANCEL_CURRENT);
    builder.setContentIntent(pendingIntent);
    builder.setOngoing(true);
    builder.setAutoCancel(false);
    builder.setContentTitle("Sample Service");
    Notification notification = builder.build();
    notification.icon = R.drawable.ic_launcher;
    notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
    startForeground(NOTIFICATION_ID, notification);
    return START_STICKY;
}

but this Service getting killed when app is swiped off from recent tasks even though it is a foreground Service.

Any help is appreciated.

RuntimeException
  • 1,201
  • 3
  • 14
  • 25

5 Answers5

2

Looking at this comment about the Android bug, I found this solution that solve the problem for me!

AlarmManager almgr = (AlarmManager)MyContext.getSystemService(Context.ALARM_SERVICE);
Intent timerIntent = new Intent(MyUniqueLabel);
timerIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
PendingIntent pendingOffLoadIntent = PendingIntent.getBroadcast(MyContext, 1, timerIntent, 0);

you MUST do these things for it to work.

1.) Call addFlags and the intent and pass it in FLAG_RECEIVER_FORGROUND

2.) Use a non-zero request code in PendingIntent.getBroadcast

If you leave any of those steps out it will not work.

Community
  • 1
  • 1
matteolel
  • 519
  • 4
  • 14
0

There's a bug in android that describes the same issue you're facing: https://code.google.com/p/android/issues/detail?id=53313

Also, there's a lot of info on the matter in SO:

Foreground service being killed by Android

Service being killed while holding wake lock and after calling startForeground

Community
  • 1
  • 1
brunorey
  • 2,135
  • 1
  • 18
  • 26
0

Check your service to see if you have overriden the onTaskRemoved() method. Make sure you are not calling stopSelf() method there.

Rajesh
  • 654
  • 5
  • 8
-2

add below code in your manifest file

     <service
        android:name="com.example.service.NameOfYourService"
        android:process=":remote" >
    </service>
Vaishali Sutariya
  • 5,093
  • 30
  • 32
-2

use the service onTaskRemoved() method.

jinnybrain
  • 30
  • 1
  • 2