可以关注:https://gitee.com/cainiao89/AndroidKotlin 会将java 代码一起上传
package com.tmsb.app.base
import android.content.BroadcastReceiver
import android.content.IntentFilter
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import java.lang.ref.WeakReference
/**
* 基础广播类 需要传入FragmentActivity
*目的 就是为 用户只需要在 视图 中执行BaseBroadcastReceiver(activity).addRegisterReceiver
* 之后就可以了,至于后续的 UnRegisterReceiver 可以通过 lifecycle 进行监听 在触发 ON_DESTROY 的时候进行销毁
*
* 刘隽
*/
abstract class BaseBroadcastReceiver(activity: FragmentActivity) :
BroadcastReceiver() {
/**
* 弱引用 宿主 activity 消失 则一起销毁
*/
private val mActivity: WeakReference<FragmentActivity>
/**
* 添加广播事件
* @param filter
*/
fun addRegisterReceiver(filter: IntentFilter) {
mActivity.get()?.registerReceiver(this, filter)
}
/**
* 添加移除广播事件
*/
private fun addUnRegisterReceiver() {
mActivity.get()?.lifecycle?.addObserver(LifecycleEventObserver { source, event->
if (event == Lifecycle.Event.ON_DESTROY) {
mActivity.get()?.unregisterReceiver(this@BaseBroadcastReceiver)
}
})
}
init {
mActivity = WeakReference(activity)
}
}