Can't start activity from BroadcastReceiver on android 10

前端 未结 3 1428
长发绾君心
长发绾君心 2020-12-05 21:06

I updated my OS version to android 10 last night, and since then the startActivity function inside the broadcast receiver is doing nothing. This is how I try to start the ac

3条回答
  •  隐瞒了意图╮
    2020-12-05 22:00

    Android 10's restriction on background activity starts was announced about six months ago. You can read more about it in the documentation.

    Use a high-priority notification, with an associated full-screen Intent, instead. See the documentation. This sample app demonstrates this, by using WorkManager to trigger a background event needing to alert the user. There, I use a high-priority notification instead of starting the activity directly:

    val pi = PendingIntent.getActivity(
      appContext,
      0,
      Intent(appContext, MainActivity::class.java),
      PendingIntent.FLAG_UPDATE_CURRENT
    )
    
    val builder = NotificationCompat.Builder(appContext, CHANNEL_WHATEVER)
      .setSmallIcon(R.drawable.ic_notification)
      .setContentTitle("Um, hi!")
      .setAutoCancel(true)
      .setPriority(NotificationCompat.PRIORITY_HIGH)
      .setFullScreenIntent(pi, true)
    
    val mgr = appContext.getSystemService(NotificationManager::class.java)
    
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
      && mgr.getNotificationChannel(CHANNEL_WHATEVER) == null
    ) {
      mgr.createNotificationChannel(
        NotificationChannel(
          CHANNEL_WHATEVER,
          "Whatever",
          NotificationManager.IMPORTANCE_HIGH
        )
      )
    }
    
    mgr.notify(NOTIF_ID, builder.build())
    

提交回复
热议问题