在Android 12中,Google更改了音频焦点行为,导致背景音频服务停止工作。可以通过以下代码示例解决此问题:
在启动服务时添加以下代码:
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
startForegroundService(new Intent(this, YourService.class));
}else{
startService(new Intent(this, YourService.class));
}
在服务中添加以下代码:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Notification.Builder builder = new Notification.Builder(this, YOUR_NOTIFICATION_CHANNEL_ID)
.setSmallIcon(R.drawable.your_icon)
.setContentTitle(YOUR_CONTENT_TITLE)
.setContentText(YOUR_CONTENT_TEXT);
NotificationChannel channel = new NotificationChannel(YOUR_NOTIFICATION_CHANNEL_ID, YOUR_CHANNEL_NAME, YOUR_IMPORTANCE);
channel.setDescription(YOUR_CHANNEL_DESCRIPTION);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
startForeground(YOUR_NOTIFICATION_ID, builder.build());
}
其中,YOUR_NOTIFICATION_CHANNEL_ID是通知渠道的ID,YOUR_NOTIFICATION_ID是通知的ID,YOUR_CONTENT_TITLE是通知的标题,YOUR_CONTENT_TEXT是通知的内容,YOUR_CHANNEL_NAME是通知渠道的名称,YOUR_CHANNEL_DESCRIPTION是通知渠道的描述,YOUR_IMPORTANCE是通知渠道的重要性级别。
此代码示例可以将服务设置为前台服务,从而避免在Android 12中的背景音频服务停止工作的问题。