Android日期变化广播,Android中的日期和时间更改侦听器?

为了检测日期的变化,您需要注册以下操作:

这是我写的一个解决方案,所以你要做的就是扩展类,并在Activity / Fragment上注册和取消注册:abstract class DateChangedBroadcastReceiver : BroadcastReceiver() {

private var curDate = LocalDate.now()

/**called when the receiver detected the date has changed. You should still check it yourself, because you might already be synced with the new date*/

abstract fun onDateChanged(previousDate: LocalDate, newDate: LocalDate)

@Suppress("MemberVisibilityCanBePrivate")

fun register(context: Context, date: LocalDate) {

curDate = date

val filter = IntentFilter()

filter.addAction(Intent.ACTION_TIME_CHANGED)

filter.addAction(Intent.ACTION_DATE_CHANGED)

filter.addAction(Intent.ACTION_TIMEZONE_CHANGED)

context.registerReceiver(this, filter)

val newDate = LocalDate.now()

if (newDate != curDate) {

curDate = newDate

onDateChanged(date, newDate)

}

}

/**a convenient way to auto-unregister when activity/fragment has stopped. This should be called on the onResume method of the fragment/activity*/

fun registerOnResume(activity: AppCompatActivity, date: LocalDate, fragment: androidx.fragment.app.Fragment? = null) {

register(activity, date)

val lifecycle = fragment?.lifecycle ?: activity.lifecycle

lifecycle.addObserver(object : LifecycleObserver {

@Suppress("unused")

@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)

fun onPause() {//                Log.d("AppLog", "onPause, so unregistering")

lifecycle.removeObserver(this)

activity.unregisterReceiver(this@DateChangedBroadcastReceiver)

}

})

}

override fun onReceive(context: Context, intent: Intent) {

val newDate = LocalDate.now()//        Log.d("AppLog", "got intent:" + intent.action + " curDate:" + curDate + " newDate:" + newDate)

if (newDate != curDate) {//            Log.d("AppLog", "cur date is different, so posting event")

val previousDate = curDate

curDate = newDate

onDateChanged(previousDate, newDate)

}

}}

如果您不能使用LocalDate(因为它使用相对较新的API:26,目前在大约21%的设备上使用),您可以使用它:abstract class DateChangedBroadcastReceiver : BroadcastReceiver() {

private var curDate = Calendar.getInstance()

/**called when the receiver detected the date has changed. You should still check it yourself, because you might already be synced with the new date*/

abstract fun onDateChanged(previousDate: Calendar, newDate: Calendar)

companion object {

fun toString(cal: Calendar): String {

return "${cal.get(Calendar.YEAR)}-${cal.get(Calendar.MONTH)}-${cal.get(Calendar.DAY_OF_MONTH)}"

}

fun resetDate(date: Calendar) {

date.set(Calendar.HOUR_OF_DAY, 0)

date.set(Calendar.MINUTE, 0)

date.set(Calendar.SECOND, 0)

date.set(Calendar.MILLISECOND, 0)

}

fun areOfSameDate(date: Calendar, otherDate: Calendar) =

date.get(Calendar.DAY_OF_YEAR) == otherDate.get(Calendar.DAY_OF_YEAR) &&

date.get(Calendar.YEAR) == otherDate.get(Calendar.YEAR)

}

@Suppress("MemberVisibilityCanBePrivate")

fun register(context: Context, date: Calendar) {

curDate = date.clone() as Calendar

resetDate(curDate)

val filter = IntentFilter()

filter.addAction(Intent.ACTION_TIME_CHANGED)

filter.addAction(Intent.ACTION_DATE_CHANGED)

filter.addAction(Intent.ACTION_TIMEZONE_CHANGED)

context.registerReceiver(this, filter)

val newDate = Calendar.getInstance()

resetDate(newDate)

if (!areOfSameDate(newDate, curDate)) {

val previousDate = curDate.clone() as Calendar

curDate = newDate

onDateChanged(previousDate, curDate)

}

}

/**a convenient way to auto-unregister when activity/fragment has stopped. This should be called on the onResume method of the fragment/activity*/

fun registerOnResume(activity: AppCompatActivity, date: Calendar, fragment: Fragment? = null) {

register(activity as Context, date)

val lifecycle = fragment?.lifecycle ?: activity.lifecycle

lifecycle.addObserver(object : LifecycleObserver {

@Suppress("unused")

@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)

fun onPause() {//                Log.d("AppLog", "onPause, so unregistering")

lifecycle.removeObserver(this)

activity.unregisterReceiver(this@DateChangedBroadcastReceiver)

}

})

}

override fun onReceive(context: Context, intent: Intent) {

val newDate = Calendar.getInstance()

resetDate(newDate)//        Log.d("AppLog", "got intent:${intent.action} curDate:${toString(curDate)} newDate:${toString(newDate)}")

if (!areOfSameDate(newDate, curDate)) {//            Log.d("AppLog", "cur date is different, so posting event")

val previousDate = curDate.clone() as Calendar

curDate = newDate

onDateChanged(previousDate, newDate)

}

}}

用法示例:class MainActivity : AppCompatActivity() {

var curDate = Calendar.getInstance()

override fun onCreate(savedInstanceState: Bundle?) {

super.onCreate(savedInstanceState)

setContentView(R.layout.activity_main)

}

override fun onResume() {

super.onResume()

object : DateChangedBroadcastReceiver() {

override fun onDateChanged(previousDate: Calendar, newDate: Calendar) {

Log.d("AppLog", "MainActivity: ${DateChangedBroadcastReceiver.toString(previousDate)} -> ${DateChangedBroadcastReceiver.toString(newDate)}")

curDate = newDate.clone() as Calendar

//TODO handle date change

}

}.registerOnResume(this, curDate)

}}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值