Android屏幕解锁后前台服务被杀死

Foreground Service get killed after Android Screen Unlock

我正在前台服务中播放音乐,它与 Activity 有界,当 Activity 运行时,如果屏幕关闭并再次打开,服务不会终止,但是
当活动不可见时意味着音乐仅在前台服务中运行并且应用程序关闭而音乐在后台播放并且当我关闭屏幕时音乐播放正常但是当我解锁屏幕时它杀死了服务


在@corsair992 评论中提供的页面上查看此评论,我找到了为我解决问题的解决方案!

1
2
3
4
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.