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