某年某月某日在VLC的库源码里面看到的,总结一下
public class WeakHandler<T extends WeakHandler.MessageListener> extends Handler {
private final WeakReference<T> mHandlerReference;
public WeakHandler(T owner) {
mHandlerReference = new WeakReference<>(owner);
}
@Override
public void handleMessage(Message msg) {
final T owner = getOwner();
if (owner != null) {
owner.handleMessage(msg);
}
}
public interface MessageListener {
public void handleMessage(Message msg);
}
public T getOwner() {
return this.mHandlerReference.get();
}
public void clear() {
mHandlerReference.clear();
}
}
在activity里面使用
public class HandlerActivity extends Activity implements MyWeakHandler.MessageListener {
private static MyWeakHandler<HandlerActivity> sHandler;//设置成静态成员,否则会出现内存泄漏
public static final int MSG_ON_A = 0x111;
public static final int MSG_ON_B = 0x112;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sHandler = new MyWeakHandler<>(this);
}
@Override
protected void onDestroy() {
super.onDestroy();
sHandler.removeCallbacksAndMessages(null);//清除所有未处理的消息
sHandler.clear();
sHandler=null;
}
private void backgroundWorkA() {
.....
//耗时操作,一般在线程的run方法或者Android系统框架回调放方法,比如低功耗蓝牙 BluetoothAdapter.LeScanCallback的 onLeScan()回调方法
sHandler.obtainMessage(MSG_ON_A).sendToTarget();
.....
}
private void backgroundWorkB() {
....
//耗时操作
sHandler.obtainMessage(MSG_ON_B).sendToTarget();
.....
}
@Override
public void handleMessage(Message msg) {
switch (msg.what) { //处理各种消息
case MSG_ON_A:
break;
case MSG_ON_B:
break;
}
}
}