当应用程序处于后台时,如何从 BroadcastReceiver 的 onReceive() 方法启动 activity?

How to start an activity from BroadcastReceiver's onReceive() method when app is in background?

我想从 BroadcastReceiver 的 onReceive() 方法启动一个 activity。这是我正在使用的代码:

class TimeReminderReceiver : BroadcastReceiver() {
     override fun onReceive(p0: Context?, p1: Intent?) {
         println("RECEIVED")

         val i = Intent(p0!!, TimeReminderActivity::class.java)
         i.flags = Intent.FLAG_ACTIVITY_NEW_TASK
         p0.startActivity(i)
     }
}

这个问题在 Whosebug 中有很多答案,我都试过了,none 对我有用。该应用程序只打印 RECEIVED 并留在那里。 logcat 没有任何显示,无一例外。我也在mainfest中添加了接收器。

<receiver
        android:name=".receivers_and_activities.TimeReminderReceiver" />

这段代码有什么问题?

编辑:

调用广播的代码:

val intent = Intent(this@MainActivity, TimeReminderReceiver::class.java)
val pendingIntent = PendingIntent.getBroadcast(this@MainActivity, 0, intent,
                    PendingIntent.FLAG_UPDATE_CURRENT)
val am = this@MainActivity.getSystemService(Context.ALARM_SERVICE) as AlarmManager
am.set(AlarmManager.RTC_WAKEUP, calendar.timeInMillis, pendingIntent)

正如您所评论的那样,当您的应用在 Android 10 (API 29级).

从 Android(API 级别 29)开始,当您的应用程序处于后台时,他们对打开 Activity 设置了一些限制。

Android 10 (API level 29) and higher place restrictions on when apps can start activities when the app is running in the background.

你可以在这里找到 Restrictions on starting activities from the background

他们也提到了

In nearly all cases, apps that are in the background should display time-sensitive notifications to provide urgent information to the user instead of directly starting an activity. Examples of when to use such notifications include handling an incoming phone call or an active alarm clock.

因此,为了克服这种行为,而不是在应用程序处于后台时调用您的应用程序,您应该显示 高优先级通知 并具有 全屏意图.

关于高优先级通知和全屏Intent的更多信息,您可以在这里查看Display time-sensitive notifications