【发布时间】:2019-10-24 06:22:48
【问题描述】:
我的应用中有 AlarmNotification,每次它出现时我都想点击它并从后台打开父 Activity/wakeup 应用。为什么它不起作用?它会在特定时间显示通知,因此警报部分按预期工作,但它不会在点击时执行任何操作。
首先我必须创建通知:
private fun createNotification(){
val vibrateFreq = longArrayOf(1000, 1000, 1000, 1000, 1000)
nb = NotificationCompat.Builder(a, channelId)
.setSmallIcon(R.drawable.logo)
.setContentTitle(title)
.setContentText(text)
.setVibrate(vibrateFreq)
.setStyle(NotificationCompat.BigTextStyle().bigText(textLong))
.setAutoCancel(true)
}
然后我需要注册闹钟以在特定时间显示通知:
private fun createAlarm(){
val pInt = app.createAlarmPendingIntent(a, nb)
val cal = Calendar.getInstance()
cal.add(Calendar.MINUTE, delta)
app.aManager.set(AlarmManager.RTC_WAKEUP, cal.timeInMillis, pInt)
}
fun createAlarmPendingIntent(a: Activity, nb: NotificationCompat.Builder?): PendingIntent{
val nInt = Intent(a, AlarmReceiver::class.java)
nInt.putExtra(
AlarmReceiver.NOTIFICATION_ID,
AlarmNotification.NOTIFICATION_NAME
)
nInt.putExtra(AlarmReceiver.NOTIFICATION, nb?.build())
val pInt = PendingIntent.getBroadcast(
a,
0,
nInt,
PendingIntent.FLAG_UPDATE_CURRENT
)
return pInt
}
然后会触发BroadcastReceiver打开通知:
class AlarmReceiver: BroadcastReceiver(){
companion object{
const val NOTIFICATION_ID = "20288855447-99899"
const val NOTIFICATION = "alarmNotify"
}
override fun onReceive(context: Context?, intent: Intent?) {
val notificationManager = context?.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val notification: Notification? = intent?.getParcelableExtra(NOTIFICATION)
val id = intent?.getIntExtra(NOTIFICATION_ID, 0)
id?.let {
notificationManager.notify(id, notification)
}
}
}
【问题讨论】:
-
从哪里调用/传递父活动/唤醒应用?
-
默认情况下,将触发 HOME/Launcher 屏幕。您需要根据参数打开所需的屏幕。
-
此通知每次都会在启动器活动中创建。它假设每次都打开 Launcher Activity。
标签: android broadcastreceiver android-notifications android-pendingintent