This Handler class should be static or leaks maight occur
阿新 • • 發佈:2018-11-27
在使用Handler更新UI的時候出現警告:
意思是說:這個Handler 必須是static的,否則就會引發記憶體洩露。
解決:
讓Handler持有一個對Activity的WeakReference,這樣就不會洩露Activity的上下文了:
public class TestActivity extends AppCompatActivity {
private final MyHandler mMyHandler = new MyHandler(this);
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super .onCreate(savedInstanceState);
mMyHandler.postDelayed(new Runnable() {
@Override
public void run() {
// TODO: 2018/3/2
}
}, 60 * 10 * 1000);
}
private static class MyHandler extends Handler {
private WeakReference<TestActivity> mWeakReference = null ;
private MyHandler(TestActivity activity) {
mWeakReference = new WeakReference<TestActivity>(activity);
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
TestActivity activity = mWeakReference.get();
if (activity != null) {
// TODO: 2018/3/2
}
}
}
}