foreground service getting killed when app is swip

2019-06-01 05:01发布

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.

4条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-06-01 05:29

use the service onTaskRemoved() method.

查看更多
狗以群分
3楼-- · 2019-06-01 05:38

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.

查看更多
成全新的幸福
4楼-- · 2019-06-01 05:45

add below code in your manifest file

     <service
        android:name="com.example.service.NameOfYourService"
        android:process=":remote" >
    </service>
查看更多
Viruses.
5楼-- · 2019-06-01 05:51
登录 后发表回答