为什么检查AndroidKotlin通知是否存在总是返回true?

nkoocmlb  于 2023-10-23  发布在  Kotlin
关注(0)|答案(1)|浏览(106)

为了避免每次都创建通知,我创建了这个方法:

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以前从未调用过

tzcvj98z

tzcvj98z1#

单独使用FLAG_IMMUTABLE不会检查PendingIntent是否已经存在-它只会使其不可变。您仍然需要FLAG_NO_CREATE

val intFlags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    PendingIntent.FLAG_NO_CREATE or PendingIntent.FLAG_IMMUTABLE
} else {
    PendingIntent.FLAG_NO_CREATE
}

还要确保您在checkAlarm()setAlarm()之间使用的notificationId是一致的。

相关问题