在Java語言中,直接將Handler聲明為Activity的內部類去使用Handler,非靜態內部類會持有外部類的一個隱試引用,這樣就可能造成外部類無法被垃圾回收,(Handler應認為是屬於內核的對象,內核和activity所在線程是異步的,當Activity被銷毀時內核可能還在用這個Handler,於是內核不讓釋放Handler,於是這個Handler沒用了,卻錯過了唯一一次被銷毀 的機會,就這樣占據着內存)從而導致內存泄漏。
故而,給出規范的Handler使用方式如下:
1.定義一個Handler 的import android.os.Handler;
import android.os.Handler; import java.lang.ref.WeakReference; /** * @author Harper * @date 2021/11/11 * note: */ public class UiHandler<T> extends Handler { protected WeakReference<T> ref; public UiHandler(T cla) { ref = new WeakReference<>(cla); } public T getRef() { return ref != null ? ref.get() : null; } }
2.Handler在Activity中使用實例:
private final MyHandler mHandler = new MyHandler(this); public static void startActivity(Context context) { Intent intent = new Intent(context, HandleActivity.class); context.startActivity(intent); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_handle); mHandler.post(RUNNABLE); } private static final Runnable RUNNABLE = () -> { }; private static class MyHandler extends UiHandler<HandleActivity> { private MyHandler(HandleActivity activity) { super(activity); } @Override public void handleMessage(@NonNull Message msg) { super.handleMessage(msg); HandleActivity activity = getRef(); if (activity != null) { if (activity.isFinishing()) { return; } int msgId = msg.what; if (msgId == 1) { //處理消息 } } } }