当前位置 : 主页 > 编程语言 > java >

【Android,Kotlin】教你写一个弱引用的Handler工具,避免内存泄漏

来源:互联网 收集:自由互联 发布时间:2022-06-30
教你写一个弱引用的Handler工具类,避免内存泄漏 Crazy Coding UtilKHandler open class UtilKHandlerT(cls: T) : Handler(Looper.getMainLooper()) { var ref: WeakReferenceT? = null init { ref = WeakReference(cls) } /** * 获取UIHa


教你写一个弱引用的Handler工具类,避免内存泄漏

Crazy Coding

UtilKHandler

open class UtilKHandler<T>(cls: T) : Handler(Looper.getMainLooper()) {
var ref: WeakReference<T>? = null

init {
ref = WeakReference(cls)
}

/**
* 获取UIHandler
* @return T?
*/
fun getRef(): T? {
return ref?.get()
}
}

How To Use

UtilKHandler(this@RefreshKLayoutActivity).postDelayed(1000) { vb.refreshkContainer.refreshFinished() }

​​还可以写一个扩展函数,搭配使用​​

/**
* postDelay
* @receiver Handler
* @param delayMills Long
* @param runnable Runnable
*/
fun Handler.postDelayed(delayMills: Long, runnable: Runnable) {
this.postDelayed(runnable, delayMills)
}

/**
* 插到队首
* @receiver Handler
* @param runnable Runnable
*/
fun Handler.sendAtFrontOfQueue(runnable: Runnable) {
val msg = Message.obtain(this, runnable)
this.sendMessageAtFrontOfQueue(msg)
}

/**
* 移除
* @receiver Handler
* @param runnable Runnable
*/
fun Handler.remove(runnable: Runnable) {
this.removeCallbacks(runnable)
}


上一篇:【Android,gradle】功能性依赖整理
下一篇:没有了
网友评论