在android中检测广播接收器中的日期变化事件

时间:2014-12-07 13:03:35

标签: android broadcast receiver

我想在Android应用程序中实现一个功能,即使我的应用程序没有运行,也会在有日期更改时(00:00 AM)执行特定代码。

2 个答案:

答案 0 :(得分:12)

我可能会迟到回答这个问题,但我个人也遇到了同样的问题。对于日期更改,您可以简单地使用带有操作" android.intent.action.DATE_CHANGED"的广播接收器,并且只要日期更改(用户隐式或显式),它就会触发。我希望这可以帮助那些通过谷歌来到这里的人。

答案 1 :(得分:0)

要完成@ gaurav-jain回答,在这里,我有一个例子,以检测日期是否已更改:

abstract class DayChangedBroadcastReceiver : BroadcastReceiver() {

    private var date = Date()
    private val dateFormat by lazy { SimpleDateFormat("yyMMdd", Locale.getDefault()) }

    override fun onReceive(context: Context, intent: Intent) {
        val action = intent.action

        val currentDate = Date()

        if ((action == Intent.ACTION_TIME_CHANGED || action == Intent.ACTION_TIMEZONE_CHANGED) && !isSameDay(currentDate)) {
            date = currentDate
            onDayChanged()
        }
    }

    private fun isSameDay(currentDate: Date) = dateFormat.format(currentDate) == dateFormat.format(date)

    abstract fun onDayChanged()

    companion object {

        /**
         * Create the [IntentFilter] for the [DayChangedBroadcastReceiver].
         *
         * @return The [IntentFilter]
         */
        fun getIntentFilter() = IntentFilter().apply {
            addAction(Intent.ACTION_TIME_TICK)
            addAction(Intent.ACTION_TIMEZONE_CHANGED)
            addAction(Intent.ACTION_TIME_CHANGED)
        }
    }
}

在活动中创建DayChangedBroadcastReceiver

private val dayChangedBroadcastReceiver = object : DayChangedBroadcastReceiver() {

        override fun onDayChanged() {
            // TODO Reload data
        }
    }

注册您的活动/片段:

 override fun onResume() {
        super.onResume()
        activity?.registerReceiver(dayChangedBroadcastReceiver, DayChangedBroadcastReceiver.getIntentFilter())
    }

取消注册您的活动/片段:

    override fun onPause() {
        super.onPause()
        activity?.unregisterReceiver(dayChangedBroadcastReceiver)
    }