gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 08:51:23 24 4
gpt4 key购买 nike

我想从 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)
}
}

这个问题在 stackoverflow 中有很多答案,我都试过了,但没有一个对我有用。该应用程序只是打印 RECEIVED 并停留在那里。 logcat 上什么也没有显示,无一异常(exception),什么也没有。我也在 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) 上处于后台时,您正在尝试启动一个 Activity。

从 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 高优先级通知

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

关于android - 当应用程序处于后台时,如何从 BroadcastReceiver 的 onReceive() 方法启动 Activity ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60182376/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com