问题来源于 Android 12 更严格的后台限制。应用在后台运行时,Twilio Video SDK 通过启用后台服务来维持其会话,并且在 Android 12 上需要满足额外的条件。
解决方法是使用新的后台服务 API,并修改 Twilio Video SDK 的代码以适应 Android 12 的后台限制。以下是一个示例代码,演示如何在 Android 12 上保持 Twilio Video 会话:
// Manifest Declare Service
// Service Code public class NotificationService extends Service { @Override public int onStartCommand(Intent intent, int flags, int startId) { startForeground(NOTIFICATION_ID, new Notification()); stopForeground(true); return START_NOT_STICKY; }
@Override public IBinder onBind(Intent intent) { return null; } }
// MainActivity Code private fun createNotification() { val notification = Notification.Builder(this, channelId) .setContentTitle("Title") .setContentText("Text") .setSmallIcon(R.drawable.icon)
val intent = Intent(this, TwilioVideoService::class.java) intent.putExtra(TwilioVideoService.EXTRA_NOTIFICATION_STOP, true) val pendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
notification.addAction(Notification.Action.Builder( Icon.createWithResource(this, R.drawable.stop), "Stop", pendingIntent).build())
startForeground(NOTIFICATION_ID, notification.build())
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { // startForegroundService does not set the foreground notification icon on Android API level >= 26 startService(Intent(this, NotificationService::class.java)) } }
// TwilioVideoService Code override fun onBind(intent: Intent?): IBinder? = null
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { if (intent?.getBooleanExtra(EXTRA_NOTIFICATION_STOP, false) == true) { stopForeground(true