为了避免每次都创建通知,我创建了这个方法:
fun checkAlarm(context: Context): Boolean {
val alarmIntent = Intent(context, NotifierReceiver::class.java)
alarmIntent.action = ACTION_BD_NOTIFICATION
val intFlags = if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
PendingIntent.FLAG_IMMUTABLE
}
else{
PendingIntent.FLAG_NO_CREATE
}
return PendingIntent.getBroadcast(
context, notificationId,
alarmIntent,
intFlags
) != null
}
这是集合方法
fun setAlarm(context: Context, notificationFrequency: Long) {
val notificationFrequencyMs = TimeUnit.MINUTES.toMillis(notificationFrequency)
alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
val alarmIntent = Intent(context, NotifierReceiver::class.java)
alarmIntent.action = ACTION_BD_NOTIFICATION
val intFlags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
}
else{
PendingIntent.FLAG_UPDATE_CURRENT
}
val pendingAlarmIntent = PendingIntent.getBroadcast(
context,
notificationId,
alarmIntent,
intFlags
)
alarmManager!!.setRepeating(
AlarmManager.RTC_WAKEUP,
System.currentTimeMillis(),
notificationFrequencyMs,
pendingAlarmIntent
)
/* Restart if rebooted */
val receiver = ComponentName(context, BootReceiver::class.java)
context.packageManager.setComponentEnabledSetting(
receiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP
)
}
在我的片段中,我称之为:
if (!alarm.checkAlarm(requireContext()) && notificationIsActive) {
alarm.setAlarm(
requireContext(),
30
)
}
checkAlarm总是返回true,而通知从来没有设置过,这怎么可能呢?我在片段的OnStart中调用此方法,并且setAlarm以前从未调用过
1条答案
按热度按时间tzcvj98z1#
单独使用
FLAG_IMMUTABLE
不会检查PendingIntent
是否已经存在-它只会使其不可变。您仍然需要FLAG_NO_CREATE
:还要确保您在
checkAlarm()
和setAlarm()
之间使用的notificationId
是一致的。