热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

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

为了检测日期的变化,您需要注册以下操作:这是我写的一个解决方案,所以你要做的就是扩展类,并在ActivityFragment

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

这是我写的一个解决方案,所以你要做的就是扩展类,并在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)

}}



推荐阅读
  • 本文介绍了RxJava在Android开发中的广泛应用以及其在事件总线(Event Bus)实现中的使用方法。RxJava是一种基于观察者模式的异步java库,可以提高开发效率、降低维护成本。通过RxJava,开发者可以实现事件的异步处理和链式操作。对于已经具备RxJava基础的开发者来说,本文将详细介绍如何利用RxJava实现事件总线,并提供了使用建议。 ... [详细]
  • Iamtryingtomakeaclassthatwillreadatextfileofnamesintoanarray,thenreturnthatarra ... [详细]
  • 在Android开发中,使用Picasso库可以实现对网络图片的等比例缩放。本文介绍了使用Picasso库进行图片缩放的方法,并提供了具体的代码实现。通过获取图片的宽高,计算目标宽度和高度,并创建新图实现等比例缩放。 ... [详细]
  • ZSI.generate.Wsdl2PythonError: unsupported local simpleType restriction ... [详细]
  • XML介绍与使用的概述及标签规则
    本文介绍了XML的基本概念和用途,包括XML的可扩展性和标签的自定义特性。同时还详细解释了XML标签的规则,包括标签的尖括号和合法标识符的组成,标签必须成对出现的原则以及特殊标签的使用方法。通过本文的阅读,读者可以对XML的基本知识有一个全面的了解。 ... [详细]
  • 自动轮播,反转播放的ViewPagerAdapter的使用方法和效果展示
    本文介绍了如何使用自动轮播、反转播放的ViewPagerAdapter,并展示了其效果。该ViewPagerAdapter支持无限循环、触摸暂停、切换缩放等功能。同时提供了使用GIF.gif的示例和github地址。通过LoopFragmentPagerAdapter类的getActualCount、getActualItem和getActualPagerTitle方法可以实现自定义的循环效果和标题展示。 ... [详细]
  • 本文介绍了iOS数据库Sqlite的SQL语句分类和常见约束关键字。SQL语句分为DDL、DML和DQL三种类型,其中DDL语句用于定义、删除和修改数据表,关键字包括create、drop和alter。常见约束关键字包括if not exists、if exists、primary key、autoincrement、not null和default。此外,还介绍了常见的数据库数据类型,包括integer、text和real。 ... [详细]
  • Oracle seg,V$TEMPSEG_USAGE与Oracle排序的关系及使用方法
    本文介绍了Oracle seg,V$TEMPSEG_USAGE与Oracle排序之间的关系,V$TEMPSEG_USAGE是V_$SORT_USAGE的同义词,通过查询dba_objects和dba_synonyms视图可以了解到它们的详细信息。同时,还探讨了V$TEMPSEG_USAGE的使用方法。 ... [详细]
  • NotSupportedException无法将类型“System.DateTime”强制转换为类型“System.Object”
    本文介绍了在使用LINQ to Entities时出现的NotSupportedException异常,该异常是由于无法将类型“System.DateTime”强制转换为类型“System.Object”所导致的。同时还介绍了相关的错误信息和解决方法。 ... [详细]
  • 本文介绍了Java集合库的使用方法,包括如何方便地重复使用集合以及下溯造型的应用。通过使用集合库,可以方便地取用各种集合,并将其插入到自己的程序中。为了使集合能够重复使用,Java提供了一种通用类型,即Object类型。通过添加指向集合的对象句柄,可以实现对集合的重复使用。然而,由于集合只能容纳Object类型,当向集合中添加对象句柄时,会丢失其身份或标识信息。为了恢复其本来面貌,可以使用下溯造型。本文还介绍了Java 1.2集合库的特点和优势。 ... [详细]
  • ECMA262规定typeof操作符的返回值和instanceof的使用方法
    本文介绍了ECMA262规定的typeof操作符对不同类型的变量的返回值,以及instanceof操作符的使用方法。同时还提到了在不同浏览器中对正则表达式应用typeof操作符的返回值的差异。 ... [详细]
  • Netty源代码分析服务器端启动ServerBootstrap初始化
    本文主要分析了Netty源代码中服务器端启动的过程,包括ServerBootstrap的初始化和相关参数的设置。通过分析NioEventLoopGroup、NioServerSocketChannel、ChannelOption.SO_BACKLOG等关键组件和选项的作用,深入理解Netty服务器端的启动过程。同时,还介绍了LoggingHandler的作用和使用方法,帮助读者更好地理解Netty源代码。 ... [详细]
  • 在C#中,使用关键字abstract来定义抽象类和抽象方法。抽象类是一种不能被实例化的类,它只提供部分实现,但可以被其他类继承并创建实例。抽象类可以用于类、方法、属性、索引器和事件。在一个类声明中使用abstract表示该类倾向于作为其他类的基类成员被标识为抽象,或者被包含在一个抽象类中,必须由其派生类实现。本文介绍了C#中抽象类和抽象方法的基础知识,并提供了一个示例代码。 ... [详细]
  • 在IDEA中运行CAS服务器的配置方法
    本文介绍了在IDEA中运行CAS服务器的配置方法,包括下载CAS模板Overlay Template、解压并添加项目、配置tomcat、运行CAS服务器等步骤。通过本文的指导,读者可以轻松在IDEA中进行CAS服务器的运行和配置。 ... [详细]
  • 解决nginx启动报错epoll_wait() reported that client prematurely closed connection的方法
    本文介绍了解决nginx启动报错epoll_wait() reported that client prematurely closed connection的方法,包括检查location配置是否正确、pass_proxy是否需要加“/”等。同时,还介绍了修改nginx的error.log日志级别为debug,以便查看详细日志信息。 ... [详细]
author-avatar
手浪用户2602928711
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有