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

Foreground Service get killed after Android Screen Unlock

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

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

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.