1 Star 1 Fork 0

沉璧浮光 / BCReceiver

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README

BCReceiver

为了简化广播接收处理,封装了一下广播接收器,使用方法:

引入依赖

Step 1. Add the JitPack repository to your build file

allprojects {
	repositories {
	  ...
	  maven { url 'https://jitpack.io' }
    }
}

Step 2. Add the dependency

dependencies {
	implementation 'com.gitee.cbfg5210:BCReceiver:$version'
}

使用

1、普通用法

    BCReceiver()
		// 添加 action 等
		.withFilter { intentFilter ->
			intentFilter.addAction(Intent.ACTION_TIME_CHANGED)
			intentFilter.addAction(Intent.ACTION_TIME_TICK)
		}
		// 设置回调
		.setCallback { context, intent -> Log.e("***", "${System.currentTimeMillis()}") }
		// 自定义回调处理
		//.setBCWatcher(BCWatcher)
		//.bind(this, lifecycle) // 默认在 onCreate 注册广播接收器,在 onDestroy 注销
		//.bind(this,lifecycle,Lifecycle.Event.ON_START) // 在 onStart 注册广播接收器,在 onStop 注销
		.bind(this, lifecycle, Lifecycle.Event.ON_RESUME) // 在 onResume 注册广播接收器,在 onPause 注销

2、自定义回调处理

以时间广播为例,我们在收到时间广播后,往往需要获取当前的时间并且对其进行格式化,这时候可以实现 BCWatcher 的接口, 在其中对时间进行处理再对外提供以外回调方法以供使用即可。

BCWatcher.kt :

interface BCWatcher {
    /**
     * 创建 BCReceiver 广播接收器回调
     */
    fun create(): (context: Context, intent: Intent) -> Unit

    /**
     * 注册广播接收器时调用
     */
    fun triggerAtOnce(context: Context)
}

TimeWatcher.kt :

class TimeWatcher(
    format: String? = null,
    locale: Locale? = null,
    private val action: (timeMills: Long, formattedTime: String?) -> Unit
) : BCWatcher {
    private var dateFormat = format?.run { SimpleDateFormat(this, locale ?: Locale.getDefault()) }

    override fun create(): (context: Context, intent: Intent) -> Unit {
        return { context, _ -> triggerAtOnce(context) }
    }

    override fun triggerAtOnce(context: Context) {
        val timeMills = System.currentTimeMillis()
        val formattedTime = dateFormat?.format(timeMills)
        action(timeMills, formattedTime)
    }
}

使用 TimeWatcher:

   BCReceiver()
          .withFilter { intentFilter ->
              intentFilter.addAction(Intent.ACTION_TIME_CHANGED)
              intentFilter.addAction(Intent.ACTION_TIME_TICK)
          }
           .setBCWatcher(TimeWatcher("yyyy-MM-dd HH:mm:ss") { timeMills, formattedTime ->
	       Log.e("***", "timeMills=$timeMills,formattedTime=$formattedTime")
	   })
          .bind(this, lifecycle)

为了便利使用以及减少重复代码,依赖库中对时间广播、home 键广播、电量广播、网络广播自定义了回调处理: (:warning: 为了保持 BCReceiver 的轻量化,自 v0.2 起原内部封装的 watcher 已迁移到 BCReceiver-Watchers 中)
capture_1.png

具体使用可以看这里

空文件

简介

BroadcastReceiver 封装 展开 收起
Android
取消

发行版 (2)

全部

贡献者

全部

近期动态

加载更多
不能加载更多了
Android
1
https://gitee.com/cbfg5210/BCReceiver.git
git@gitee.com:cbfg5210/BCReceiver.git
cbfg5210
BCReceiver
BCReceiver
master

搜索帮助