Android 广播接收器未使用报警管理器触发

Android 广播接收器未使用报警管理器触发,android,kotlin,Android,Kotlin,我已经被困了好几天,试图找出我的广播接收器和报警管理器有什么问题,基本上我的广播接收器在推送通知时不会被触发 **这是我的广播接收机课 class NotificationAlarmReceiver : BroadcastReceiver() { private lateinit var mAlarmManager : AlarmManager private lateinit var mPowerManager: PowerManager override fun onR

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

**这是我的广播接收机课

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())
                   }
              } 
**我在清单文件中添加的权限

 <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 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>

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

class InternetDaysLeftAlarm@Inject构造函数(
@ApplicationContext val上下文:上下文
) {
乐趣计划报警(触发小时:Int=互联网\天数\左侧\报警\默认\触发小时){
val alarmManager=context.getSystemService(context.ALARM\u服务)作为alarmManager
val intent=intent(上下文,InternetDaysLeftReceiver::class.java)
intent.action=intent\u action\u INTERNET\u DAYS\u LEFT\u报警
val pendingIntent=pendingIntent.getBroadcast(上下文,0,意图,0)
//计算所需触发时间前的分钟数。
//将分钟转换为毫秒以进行计划。
val msUntilTriggerHour:Long=时间单位.MINUTES.toMillis(minutesUntilLocalLock(triggerHour))
//计算并添加抖动以减轻服务器上的负载
val jitter:Long=TimeUnit.MINUTES.toMillis(Random.nextInt(0420.toLong())
val alarmTimeAtUTC:Long=System.currentTimeMillis()+msUntilTriggerHour+jitter
//启用引导接收器
val bootceiver=ComponentName(上下文,bootceiver::class.java)
context.packageManager.setComponentEnabledSetting(
引导接收器,
PackageManager.COMPONENT\u ENABLED\u STATE\u ENABLED,
PackageManager.DONT_KILL_应用程序
)
//根据Android的版本,使用不同的功能设置警报。
//setAlarmClock()=>Android<棉花糖
//setExactAndAllowHileidle()=>Android>=棉花糖
if(android.os.Build.VERSION.SDK_INT
谢谢您的回答,什么是放置报警管理器代码的最佳位置?现在我把它放在我的receiver类中,我应该把它切换到main Activity吗?好吧,我处理它的方式是我创建了一个单独的类
Alarms
,然后里面有一些函数可以安排我需要的报警。我将用一个例子来编辑我的帖子。谢谢,我知道我的问题还没有解决,我已经创建了一个单独的类,名为AlarmHelper,我在其中设置了报警管理,然后在我的主要活动中调用它,它仍然只在我重新启动应用程序时起作用。你说的“当我重新启动应用程序时”是什么意思?比如说,当应用程序启动时,你已经安排好了闹钟。它计划在前台应用程序启动后30秒运行。它是在发射30秒后触发的吗?

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 

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
            )
        }
    }
}