根据谷歌文档。 https://developer.android.com/reference/android/app/AlarmManager.html“警报管理器适用于您希望应用程序代码在特定时间运行的情况,即使您的应用程序不是目前正在运行。”这正是我的用例。我在未来几分钟内在我的应用程序设置中使用 PendingIntent 创建警报,然后关闭应用程序。操作系统需要通过广播传递意图并唤醒我的应用程序。一旦 Intent 传递到应用程序,应用程序就会触发一些内部函数。如果我的应用程序一直运行,则一切正常: 相关代码:
//Alarm creation
val alarmManager =
myApp.applicationContext().getSystemService(Context.ALARM_SERVICE) as AlarmManager
if (alarmManager.canScheduleExactAlarms()) {
try {
val alarmIntent = PendingIntent.getBroadcast(
myApp.applicationContext(),
id,
intent,
PendingIntent.FLAG_CANCEL_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
alarmManager.setExact(
AlarmManager.RTC_WAKEUP,
triggerAtMillis, // few mins in the future
alarmIntent
)
} catch (e: SecurityException) {
// Print error
}
// handling Intent:
class AlarmReceiver : BroadcastReceiver() {
var context: Context = myApp.applicationContext()
override fun onReceive(context: Context, intent: Intent) {
// do stuff here
}
申请有
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
<uses-permission android:name="android.permission.USE_EXACT_ALARM" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
我运行Android 12,设备是一个一直供电的电视盒(无电池),拥有WakeLock。
任何关于 Android 不启动我的应用程序并传递 PendingIntent 的想法。我觉得我做错了什么,但不知道是什么......谢谢 大卫