教你写一个弱引用的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)
}