这可能是 Android 13 中的电池优化所导致的。可以尝试在后台服务的 onStartCommand() 方法中添加以下代码:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String CHANNEL_ID = "my_channel_01";
NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT);
((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(channel);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Title")
.setContentText("Content")
.build();
startForeground(1, notification);
} else {
startForeground(1, new Notification());
}
// 在这里添加你的服务代码
return START_STICKY;
}
这段代码会在 API 等级大于等于 26 的设备上创建一个前台服务通知,并将服务置于前台,防止服务被系统杀死。注意在 Android 8.0(API 等级 26)及以上的设备上,必须创建通知渠道。
如果你的服务已经在前台运行,可以在处理屏幕关闭事件时更新服务的通知,这样系统就不会将其杀死。可以使用以下代码:
// 在处理屏幕关闭事件的方法中添加这些代码
Notification notification = createNotification();
startForeground(NOTIFICATION_ID, notification);
同时,在你的 Manifest 文件中添加以下权限:
这应该可以解决问题,让你的服务在 Android 13 设备上保持运行。