package com.example.testhandler;
import java.lang.ref.WeakReference;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView mTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mTextView = new TextView(this);
mTextView.setText("有内存泄露");
setContentView(mTextView);
MyHandler handler = new MyHandler(mTextView);
handler.sendEmptyMessage(0x11);
}
static class MyHandler extends Handler {
WeakReference<TextView> mTextViewReference;
MyHandler(TextView textView) {
mTextViewReference = new WeakReference<TextView>(textView);
}
@Override
public void handleMessage(Message msg) {
TextView textView = mTextViewReference.get();
if (textView != null) {
textView.setText("无内存泄漏");
}
}
}
}
为以上代码作以下几点解释:
1、上述Handler的作用,是在无内存泄漏的情况下,为外部Activity的mTextView设置文本信息。
2、静态类不持有外部类的对象,所以外部Activity可以随意被回收,不会因delay的Message持有了Handler的引用,而Handler又持有Activity的引用,导致Activity被关闭后无法被GC回收。多次的打开和关闭,会造成OOM。
3、WeakReference是弱引用类型,我们可以借助弱引用类型对外部非静态变量进行操作,且Handler仅有一条弱引用指向了textView,不会影响textView的回收。
如果要对外部Activity进行操作,则可模仿上述Demo修改即可,如
static class MyHandler extends Handler {
WeakReference<Activity > mActivityReference;
MyHandler(Activity activity) {
mActivityReference= new WeakReference<Activity>(activity);
}
@Override
public void handleMessage(Message msg) {
Activity activity = mActivityReference.get();
if (activity != null) {
//...
}
}
}