android闹钟警报时,有没有最好的方式来接收通知?

时间:2019-06-14 13:17:59

标签: android

我想在用户的闹钟警报时收到通知。

所以我编写如下代码,但只收到了ALARM_DONE广播。

不同的公司采取不同的行动。

private const val ALARM_ALERT_ACTION = "com.android.deskclock.ALARM_ALERT"

private const val ALARM_DONE_ACTION = "com.android.deskclock.ALARM_DONE"

private const val TAG = "AlarmReceiver"

class AlarmReceiver private constructor(
    private val context: Context,
    private val onAlarmAlert: () -> Unit
) : BroadcastReceiver(), GenericLifecycleObserver {

    private val filter = IntentFilter().apply {
        addAction(ALARM_ALERT_ACTION)
        addAction(ALARM_DONE_ACTION)
    }

    override fun onStateChanged(source: LifecycleOwner?, event: Lifecycle.Event) {
        when (event) {
            Lifecycle.Event.ON_DESTROY -> context.unregisterReceiver(this)
            Lifecycle.Event.ON_START -> context.registerReceiver(this, filter)
        }
    }

    override fun onReceive(context: Context?, intent: Intent?) {
        Log.d(TAG, "receive broadcast: ${intent?.action}")
        if (ALARM_ALERT_ACTION == intent?.action) {
            onAlarmAlert()
        }
    }

    companion object {
        fun attach(activity: FragmentActivity, onAlarmAlert: () -> Unit) {
            val receiver = AlarmReceiver(activity, onAlarmAlert)
            activity.lifecycle.addObserver(receiver)
        }
    }
}

在活动onCreate中:

AlarmReceiver.attach(this){
   //...
}

那么,是否有最好的方式在闹钟提醒时接收通知?

0 个答案:

没有答案