How to use Android AlarmManager in Fragment in Kotlin?

六月ゝ 毕业季﹏ 提交于 2021-01-12 06:30:21

问题


I can't seem to get the AlarmManager to work inside a Fragment. My receiver's onReceive() method never gets executed. I assume that I might use context in a wrong way but then again I also couldn't get it to work inside an Activity. I've also registered the receiver in my manifest.

MyFragment.kt

class MyFragment : Fragment() {

...

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {

        super.onViewCreated(view, savedInstanceState)

        var alarmMgr: AlarmManager? = null
        lateinit var alarmIntent: PendingIntent

        alarmMgr = context!!.getSystemService(Context.ALARM_SERVICE) as AlarmManager
        alarmIntent = Intent(context, Receiver::class.java).let { intent ->

                PendingIntent.getService(context, 0, intent, 0)

        }

        val calendar: Calendar = Calendar.getInstance().apply {

        timeInMillis = System.currentTimeMillis()

        // The EditText includes a time in 24-hour format (e.g. 12:34)
        set(Calendar.HOUR_OF_DAY, editText.text.toString().substringBefore(":").toInt())
        set(Calendar.MINUTE, editText.text.toString().substringAfter(":").toInt())

        }

        Log.d("ALARM", "CREATED")

        alarmMgr?.set(
              AlarmManager.RTC,
              calendar.timeInMillis,
              alarmIntent
        )

    }

}

Receiver.kt

class Receiver : BroadcastReceiver() {

    override fun onReceive(context: Context?, intent: Intent?) {

        Log.d("ALARM", "RECEIVED")

    }

}

AndroidManifest.xml

<application
...
    <receiver android:name="com.example.name.Receiver" />
</application>

回答1:


First things first:

AndroidManifest.xml

<receiver
  android:name="com.example.name.Receiver"
  android:enabled="true"
  android:exported="true">
   <intent-filter>
    <action android:name="android.intent.action.BOOT_COMPLETED" />
    <action android:name="android.intent.action.LOCKED_BOOT_COMPLETED" />
   </intent-filter>
</receiver>

Then, in this case in your Fragment, however, I suggest doing this somewhere else:

val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
val intent = Intent(context, Receiver::class.java)

// Used for filtering inside Broadcast receiver
intent.action = "MyBroadcastReceiverAction"
val pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0)

// In this particular example we are going to set it to trigger after 30 seconds.
// You can work with time later when you know this works for sure.
val msUntilTriggerHour: Long = 30000
val alarmTimeAtUTC: Long = System.currentTimeMillis() + msUntilTriggerHour

// Depending on the version of Android use different function for setting an 
// Alarm.
// setAlarmClock() - used for everything lower than Android M
// setExactAndAllowWhileIdle() - used for everything on Android M and higher
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
  )
}

In your Broadcast Receiver, we then do the following:

class Receiver : BroadcastReceiver() {
    override fun onReceive(context: Context?, intent: Intent?) {
        // We use this to make sure that we execute code, only when this exact 
        // Alarm triggered our Broadcast receiver
        if (intent?.action == "MyBroadcastReceiverAction") {
           Log.d("ALARM", "RECEIVED")
        }
    }
}


来源:https://stackoverflow.com/questions/64268402/how-to-use-android-alarmmanager-in-fragment-in-kotlin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!