在Observer内部使用AlarmManager导致observe()仅被调用一次

时间:2019-02-20 09:56:41

标签: android mvvm alarmmanager observer-pattern android-livedata

我已经为一个带有ToggleButton的警报应用程序实现了MVVM架构,该按钮在打开时会激活警报,在关闭时会禁用警报。单击ToggleButton会在ViewModel中调用一个函数,该函数基于ToggleButton的切换状态,通过将带有警报信息的值设置为LiveData来激活或停用警报。

在片段中,我从ViewModel观察LiveData,并通过使用AlarmManager调度PendingIntent来设置警报,或者通过取消PendingIntent和AlarmManager来取消警报。问题是,当我第一次启动该应用程序时,第一次单击ToggleButton会触发Fragment中的Observer,但是此后,即使更改了LiveData值,Observer仍然拒绝触发。

我发现的是,删除与AlarmManager相关的函数(setExactAndAllowWhileIdle()/ cancel())会使Observer每次被触发,但是添加这些函数会使Observer对LiveData的任何更改均无反应。 / p>

我认为最好用代码和日志来解释。

AlarmViewModel.kt

private val newToast: MutableLiveData<SingleEvent<String>> = MutableLiveData()
private val activateEvent: MutableLiveData<SingleEvent<AlarmData>> = MutableLiveData()
private val deactivateEvent: MutableLiveData<SingleEvent<AlarmData>> = MutableLiveData()
...
private fun activateAlarm(alarmData: AlarmData) {
    newToast.value = SingleEvent("Alarm has been set!")
    activateEvent.value = SingleEvent(alarmData)
}

private fun deactivateAlarm(alarmData: AlarmData) {
    newToast.value = SingleEvent("Alarm has been cleared")
    deactivateEvent.value = SingleEvent(alarmData)
}
...
fun observeNewToast(): LiveData<SingleEvent<String>> = newToast
fun observeActivateEvent(): LiveData<SingleEvent<AlarmData>> = activateEvent
fun observeDeactivateEvent(): LiveData<SingleEvent<AlarmData>> = deactivateEvent

AlarmFragment.kt

@Inject
lateinit var alarmManager: AlarmManager
private val viewModel: SingleAlarmViewModel by lazy {
    ViewModelProviders.of(activity!!).get(AlarmViewModel::class.java)
}
private lateinit var newToastObserver: Observer<SingleEvent<String>>
private lateinit var activateEventObserver: Observer<SingleEvent<AlarmData>>
private lateinit var deactivateEventObserver: Observer<SingleEvent<AlarmData>>
...
override fun onResume() {
    super.onResume()

    newToastObserver = Observer {
        it?.getContentIfNotHandled()?.let { toastText ->
            info("observeNewToast() -> message: $toastText")
            Toast.makeText(activity, toastText, Toast.LENGTH_SHORT).show()
        }
    }

    activateEventObserver = Observer {
        it?.getContentIfNotHandled()?.let { alarmData ->
            info("activateEventObserver -> $alarmData")

            val idInteger = alarmData.timeInMillis.toInt()
            val alarmTime = alarmData.timeInMillis

            val activateAlarmIntent = Intent(activity, AlarmReceiver::class.java)
            activateAlarmIntent.putExtra("message", alarmData.toString())
            val pendingIntent = PendingIntent.getBroadcast(
                activity,
                idInteger,
                activateAlarmIntent,
                PendingIntent.FLAG_UPDATE_CURRENT
            )
            AlarmManagerCompat.setExactAndAllowWhileIdle(
                alarmManager,
                AlarmManager.RTC_WAKEUP,
                alarmTime,
                pendingIntent
            )
        }
    }

    deactivateEventObserver = Observer {
        it?.getContentIfNotHandled()?.let { alarmData ->
            info("deactivateEventObserver -> $alarmData")

            val idInteger = alarmData.timeInMillis.toInt()

            val deactivateAlarmIntent = Intent(activity, AlarmReceiver::class.java)
            deactivateAlarmIntent.putExtra("message", alarmData.toString())
            val pendingIntent = PendingIntent.getBroadcast(
                activity,
                idInteger,
                deactivateAlarmIntent,
                PendingIntent.FLAG_UPDATE_CURRENT
            )
            pendingIntent.cancel()
            alarmManager.cancel(pendingIntent)
        }
    }
    viewModel.observeNewToast().observe(activity!!, newToastObserver)
    viewModel.observeActivateEvent().observe(activity!!, activateEventObserver)
    viewModel.observeDeactivateEvent().observe(activity!!, deactivateEventObserver)
}

override fun onPause() {
    super.onPause()
    viewModel.apply {
        observeNewToast().removeObserver(newToastObserver)
        observeActivateEvent().removeObserver(activateEventObserver)
        observeDeactivateEvent().removeObserver(deactivateEventObserver)
    }
}

像这样启动应用程序时,只会观察一次activateEventObserver和deactivateEventObserver,然后停止观察,如下面的日志所示。

02-20 18:38:23.707 23671-23671/com.aly.alarm I/AlarmFragment: observeNewToast() -> message: Alarm has been cleared
02-20 18:38:23.722 23671-23671/com.aly.alarm I/AlarmFragment: deactivateEventObserver -> AlarmData(id=1, timeInMillis=1550730780000, isToggledOn=true)
02-20 18:38:28.547 23671-23671/com.aly.alarm I/AlarmFragment: observeNewToast() -> message: Alarm has been set!
02-20 18:38:28.557 23671-23671/com.aly.alarm I/AlarmFragment: activateEventObserver -> AlarmData(id=1, timeInMillis=1550730780000, isToggledOn=true)
02-20 18:38:34.647 23671-23671/com.aly.alarm I/AlarmFragment: observeNewToast() -> message: Alarm has been cleared
02-20 18:38:35.357 23671-23671/com.aly.alarm I/AlarmFragment: observeNewToast() -> message: Alarm has been set!
02-20 18:38:37.472 23671-23671/com.aly.alarm I/AlarmFragment: observeNewToast() -> message: Alarm has been cleared
02-20 18:38:38.112 23671-23671/com.aly.alarm I/AlarmFragment: observeNewToast() -> message: Alarm has been set!
02-20 18:38:38.962 23671-23671/com.aly.alarm I/AlarmFragment: observeNewToast() -> message: Alarm has been cleared
02-20 18:38:39.377 23671-23671/com.aly.alarm I/AlarmFragment: observeNewToast() -> message: Alarm has been set!

但是,如果我删除了与AlarmManager相关的代码,则将按预期方式一直调用观察者。

修改后的AlarmFragment.kt

@Inject
lateinit var alarmManager: AlarmManager
private val viewModel: SingleAlarmViewModel by lazy {
    ViewModelProviders.of(activity!!).get(AlarmViewModel::class.java)
}
private lateinit var newToastObserver: Observer<SingleEvent<String>>
private lateinit var activateEventObserver: Observer<SingleEvent<AlarmData>>
private lateinit var deactivateEventObserver: Observer<SingleEvent<AlarmData>>
...
override fun onResume() {
    super.onResume()

    newToastObserver = Observer {
        it?.getContentIfNotHandled()?.let { toastText ->
            info("observeNewToast() -> message: $toastText")
            Toast.makeText(activity, toastText, Toast.LENGTH_SHORT).show()
        }
    }

    activateEventObserver = Observer {
        it?.getContentIfNotHandled()?.let { alarmData ->
            info("activateEventObserver -> $alarmData")

            val idInteger = alarmData.timeInMillis.toInt()
            val alarmTime = alarmData.timeInMillis

            val activateAlarmIntent = Intent(activity, AlarmReceiver::class.java)
            activateAlarmIntent.putExtra("message", alarmData.toString())
            val pendingIntent = PendingIntent.getBroadcast(
                activity,
                idInteger,
                activateAlarmIntent,
                PendingIntent.FLAG_UPDATE_CURRENT
            )

            // AlarmManager code commented out
            // AlarmManagerCompat.setExactAndAllowWhileIdle(
            //     alarmManager,
            //     AlarmManager.RTC_WAKEUP,
            //     alarmTime,
            //     pendingIntent
            // )
        }
    }

    deactivateEventObserver = Observer {
        it?.getContentIfNotHandled()?.let { alarmData ->
            info("deactivateEventObserver -> $alarmData")

            val idInteger = alarmData.timeInMillis.toInt()

            val deactivateAlarmIntent = Intent(activity, AlarmReceiver::class.java)
            deactivateAlarmIntent.putExtra("message", alarmData.toString())
            val pendingIntent = PendingIntent.getBroadcast(
                activity,
                idInteger,
                deactivateAlarmIntent,
                PendingIntent.FLAG_UPDATE_CURRENT
            )
            pendingIntent.cancel()

            // AlarmManager code commented out
            // alarmManager.cancel(pendingIntent)
        }
    }
    viewModel.observeNewToast().observe(activity!!, newToastObserver)
    viewModel.observeActivateEvent().observe(activity!!, activateEventObserver)
    viewModel.observeDeactivateEvent().observe(activity!!, deactivateEventObserver)
}

override fun onPause() {
    super.onPause()
    viewModel.apply {
        observeNewToast().removeObserver(newToastObserver)
        observeActivateEvent().removeObserver(activateEventObserver)
        observeDeactivateEvent().removeObserver(deactivateEventObserver)
    }
}

这样启动应用程序时记录日志(观察到的观察者是预期的):

02-20 18:44:18.207 24565-24565/com.aly.alarm I/AlarmFragment: observeNewToast() -> message: Alarm has been cleared
02-20 18:44:18.222 24565-24565/com.aly.alarm I/AlarmFragment: deactivateEventObserver -> AlarmData(id=1, timeInMillis=1550730780000, isToggledOn=true)
02-20 18:44:18.367 24565-24565/com.aly.alarm I/AlarmFragment: observeNewToast() -> message: Alarm has been set!
02-20 18:44:18.382 24565-24565/com.aly.alarm I/AlarmFragment: activateEventObserver -> AlarmData(id=1, timeInMillis=1550730780000, isToggledOn=true)
02-20 18:44:21.277 24565-24565/com.aly.alarm I/AlarmFragment: observeNewToast() -> message: Alarm has been cleared
02-20 18:44:21.297 24565-24565/com.aly.alarm I/AlarmFragment: deactivateEventObserver -> AlarmData(id=1, timeInMillis=1550730780000, isToggledOn=true)
02-20 18:44:22.177 24565-24565/com.aly.alarm I/AlarmFragment: observeNewToast() -> message: Alarm has been set!
02-20 18:44:22.197 24565-24565/com.aly.alarm I/AlarmFragment: activateEventObserver -> AlarmData(id=1, timeInMillis=1550730780000, isToggledOn=true)
02-20 18:44:22.842 24565-24565/com.aly.alarm I/AlarmFragment: observeNewToast() -> message: Alarm has been cleared
02-20 18:44:22.857 24565-24565/com.aly.alarm I/AlarmFragment: deactivateEventObserver -> AlarmData(id=1, timeInMillis=1550730780000, isToggledOn=true)
02-20 18:44:23.447 24565-24565/com.aly.alarm I/AlarmFragment: observeNewToast() -> message: Alarm has been set!

我尝试将ViewModel生命周期所有者设置为父Activity,然后将其设置回Fragment,但没有任何区别。删除与AlarmManger相关的代码可以使观察者正常工作,但是由于我试图通过观察者来设置警报,所以这让我非常沮丧。为什么在第一次之后,AlarmManager使观察者停止观察?是在某个地方取消注册吗?

谢谢。

1 个答案:

答案 0 :(得分:0)

事实证明,这是我的完全不同的错误。.我错误地忘记了将AlarmManager注入我应该通过Dagger注入的特定片段。 感谢您的贡献!