Android 14 之 进一步限制后台启动Activity

2,859 阅读2分钟

Android 14中,发送PendingIntent 的应用绑定该应用的服务时就应该定义后台activity对于另一个应用程序的启动特权

  • 当应用程序使用 PendingIntent#send() 或类似方法发送 PendingIntent 时,如果应用程序想要授予其自己的后台活动启动权限以启动挂起的 Intent,应用应通过 setPendingIntentBackgroundActivityStartMode(MODE_BACKGROUND_ACTIVITY_START_ALLOWED) 传递 ActivityOptions 包
  • 当一个可见应用程序使用 bindService() 方法绑定另一个在后台运行的应用程序的服务时,如果该可见应用程序想要将其自己的后台活动启动权限授予绑定服务,应用程序应在调用 bindService() 方法时包含 BIND_ALLOW_ACTIVITY_STARTS 标志

当应用程序发送PendingIntentPendingIntent#send() 或类似方法时,如果应用程序想要授予其自己的后台Activity启动权限(即作为中转去启动下个PendingIntent),必须设置PendingIntent的启动模式为允许PendingIntent使用后台活动启动权限。

setPendingIntentBackgroundActivityStartMode(MODE_BACKGROUND_ACTIVITY_START_ALLOWED)
  • 示例(目前读取Build.VERSION.SDK_INT为33,无法测试该接口)
  fun showNotification1(context: Context)
    {
        intentMain =  Intent()//这个intent会传给目标,可以使用getIntent来获取
        intentMain.setClass(this, SecondActivity::class.java)

        Log.d("MainActivity", "Build.VERSION.SDK_INT:   "+Build.VERSION.SDK_INT)
        //用户点击该notification后才启动SecondActivity类
        //pi = PendingIntent.getActivity(this, 1, intentMain, PendingIntent.FLAG_IMMUTABLE);
        if (Build.VERSION.SDK_INT >= 34) {
            pi =PendingIntent.getActivity(this,1,intentMain,PendingIntent.FLAG_IMMUTABLE,activityOptions.setPendingIntentBackgroundActivityStartMode(
                ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_ALLOWED) as Bundle )
        }
        // CHANNEL_ID:通道ID,可在类 MainActivity 外自定义
        val builder = NotificationCompat.Builder(this, "chatNotification")
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentIntent(pi)
            .setContentTitle("Android 14 测试")
            .setContentText("进一步限制后台启动Activities")
            // 通知优先级,可以设置为int型,范围-2至2
            .setPriority(NotificationCompat.PRIORITY_MAX )
        // 显示通知
        with(NotificationManagerCompat.from(this)) {
    if (ActivityCompat.checkSelfPermission(
       context, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED
    ) {
                Toast.makeText(applicationContext, "没有通知权限", Toast.LENGTH_SHORT).show()
                ActivityCompat.requestPermissions(this@MainActivity,
                    arrayOf(Manifest.permission.POST_NOTIFICATIONS),1)
                    
                // TODO: Consider calling
                return
            }
            notify(1, builder.build())
        }
    }

  • 当一个可见应用程序使用 bindService() 方法绑定另一个在后台运行的应用程序的服务时,如果该可见应用程序想要将其自己的后台活动启动权限授予绑定服务,应用程序应在调用 bindService() 方法时设置BIND_ALLOW_ACTIVITY_STARTS 标志。

    bindService(Intent, Context.BindServiceFlags, Executor, ServiceConnection)