Detect day change event in broadcast receiver in a

2020-07-23 04:37发布

问题:

I want to implement a feature in android app which execute a particular code when ever there is a date change(at 00:00AM) even when my app is not running.

回答1:

I might be late answering this question, but I personally faced the same problem. For day change, you can simply use a broadcast receiver with action "android.intent.action.DATE_CHANGED", and it will trigger whenever the date is changed (either implicitly or explicitly by user). I hope this will help someone who gets to here through Google.



回答2:

To complete @gaurav-jain answer I've here an example, in this case, to detect if the day has changed:

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

Create the DayChangedBroadcastReceiver in your activity:

private val dayChangedBroadcastReceiver = object : DayChangedBroadcastReceiver() {

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

Register in your activity/fragment:

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

Unregister in your activity/fragment:

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