BroadCast Receiver没有使用警报管理器触发 [英] BroadCast Receiver is not triggering with Alarm Manager

查看:67
本文介绍了BroadCast Receiver没有使用警报管理器触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被困了好几天,试图找出广播接收器和警报管理器出了什么问题,基本上我的广播接收器在推送通知时没有被触发.

I'm stuck for days now trying to figure out what is wrong with my broadcast receiver and alarm manager , basically my broadcast receiver is not triggered when pushing a notification .

**这是我的广播接收器课程

**This is my broadcast receiver class

class NotificationAlarmReceiver : BroadcastReceiver() {

   private lateinit var mAlarmManager  : AlarmManager
   private lateinit var mPowerManager: PowerManager
   override fun onReceive(context: Context?, intent: Intent?) {

       mAlarmManager = context?.getSystemService(Context.ALARM_SERVICE) as AlarmManager
       Toast.makeText(context,"Broadcast Receiver is called",Toast.LENGTH_SHORT).show()
       
       val notificationPendingIntent = PendingIntent.getActivity(
           context, Constants.PENDINGINTENT_REQUEST_CODE,
           Intent(context, MainActivity::class.java), PendingIntent.FLAG_UPDATE_CURRENT
       )

      
       val intent = Intent(context, NotificationAlarmReceiver::class.java)
       intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND)
       val alarmPendingIntent = PendingIntent.getBroadcast(context, Constants.NOTIFICATION_ALARM_CODE, 
              intent, PendingIntent.FLAG_UPDATE_CURRENT)

                   when {
                       Build.VERSION.SDK_INT >= 23 -> {
                           mAlarmManager?.setAndAllowWhileIdle(
                               AlarmManager.ELAPSED_REALTIME_WAKEUP,
                               System.currentTimeMillis(),
                               alarmPendingIntent)
                       }
                       Build.VERSION.SDK_INT in 21..22 -> {
                           mAlarmManager.setExact(
                               AlarmManager.ELAPSED_REALTIME_WAKEUP,
                               System.currentTimeMillis(),
                               alarmPendingIntent
                           )

                       }
                   }

                 
                   NotificationCompat.Builder(context!!, Constants.NOTIFICATION_ID).apply {
                       setContentTitle("Notification Title")
                       setContentText("Notification Text")
                       setSmallIcon(R.drawable.ic_baseline_notifications_active_24)
                       setContentIntent(notificationPendingIntent)
                       setDefaults(NotificationCompat.DEFAULT_SOUND)
                       setDefaults(NotificationCompat.DEFAULT_LIGHTS)
                       setChannelId(Constants.NOTIFICATION_ID)
                       priority = NotificationCompat.PRIORITY_HIGH
                       setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                       NotificationManagerCompat.from(context!!)
                           .notify(Constants.NOTIFICATION_REQUEST_CODE, build())
                   }
              } 

**我已在清单文件中添加了权限

** Permission i have added in my manifest file

 <uses-permission android:name="android.permission.VIBRATE" />
 <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
 <uses-permission android:name="android.permission.WAKE_LOCK" />

**在清单文件中添加Receiver

** Adding Receiver in my manifest file

```

<receiver android:name=".alarmManager.NotificationAlarmReceiver">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED"/>
            <action android:name="android.intent.action.QUICKBOOT_POWERON" />
        </intent-filter>
    </receiver>


PS : I have to make a sample code to turn on / off airplane mode and registered the receiver dynamically
but with my code it is not triggered at all if anyone could guide me i d appreciate it , i ve been stuck for days 

推荐答案

您可以在此处找到工作正常的警报管理器示例:

You can find fully working examples of working Alarm Manager here:

警报管理器无法长时间使用学期任务

如何在Fragment中使用Android AlarmManager在科特林吗?

class InternetDaysLeftAlarm @Inject constructor(
    @ApplicationContext val context: Context
) {
    fun scheduleAlarm(triggerHour: Int = INTERNET_DAYS_LEFT_ALARM_DEFAULT_TRIGGER_HOUR) {
        val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
        val intent = Intent(context, InternetDaysLeftReceiver::class.java)
        intent.action = INTENT_ACTION_INTERNET_DAYS_LEFT_ALARM
        val pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0)

        // Calculating minutes until required trigger hour.
        // Converting minutes to millis for scheduling purposes.
        val msUntilTriggerHour: Long = TimeUnit.MINUTES.toMillis(minutesUntilOClock(triggerHour))

        // Calculating and adding jitter in order to ease load on server
        val jitter: Long = TimeUnit.MINUTES.toMillis(Random.nextInt(0, 420).toLong())

        val alarmTimeAtUTC: Long = System.currentTimeMillis() + msUntilTriggerHour + jitter

        // Enabling BootReceiver
        val bootReceiver = ComponentName(context, BootReceiver::class.java)
        context.packageManager.setComponentEnabledSetting(
            bootReceiver,
            PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
            PackageManager.DONT_KILL_APP
        )

        // Depending on the version of Android use different function for setting an Alarm.
        // setAlarmClock() => Android < Marshmallow
        // setExactAndAllowWhileIdle() => Android >= Marshmallow
        if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.M) {
            alarmManager.setAlarmClock(
                AlarmManager.AlarmClockInfo(alarmTimeAtUTC, pendingIntent),
                pendingIntent
            )
        } else {
            alarmManager.setExactAndAllowWhileIdle(
                AlarmManager.RTC_WAKEUP,
                alarmTimeAtUTC,
                pendingIntent
            )
        }
    }
}

这篇关于BroadCast Receiver没有使用警报管理器触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆