This Handler class should be static or leaks might occur 解决办法

首先解释下这句话This Handler class should be static or leaks might occur,大致意思就是说:Handler类应该定义成静态类,否则可能导致内存泄露。

具体如何解决,在国外有人提出,如下:

Issue: Ensures that Handler classes do not hold on to a reference to an outer class

In Android, Handler classes should be static or leaks might occur. Messages enqueued on the application thread’s MessageQueue also retain their target Handler. If the Handler is an inner class, its outer class will be retained as well. To avoid leaking the outer class, declare the Handler as a static nested class with a WeakReference to its outer class.

大体翻译如下:

Handler 类应该应该为static类型,否则有可能造成泄露。在程序消息队列中排队的消息保持了对目标Handler类的应用。如果Handler是个内部类,那 么它也会保持它所在的外部类的引用。为了避免泄露这个外部类,应该将Handler声明为static嵌套类,并且使用对外部类的弱应用。

使用范例:

public class SelectPicActivity extends Activity {
    private GridView mGroupGridView;

    private HashMap<String, List<String>> mGruopMap = new HashMap<String, List<String>>();
    private List<ImageBean> list = new ArrayList<ImageBean>();
    private final static int SCAN_OK = 1;
    private ProgressDialog mProgressDialog;
    private GroupAdapter adapter;
    private Handler mHandler = new SelectPicHandler(this);

    static class SelectPicHandler extends Handler {
        WeakReference<SelectPicActivity> mActivity;
        public SelectPicHandler(SelectPicActivity activity) {
            mActivity=new WeakReference<SelectPicActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            SelectPicActivity activity=mActivity.get();
            switch (msg.what) {
                case SCAN_OK:
                    //关闭进度条
                    activity.mProgressDialog.dismiss();
                    activity.list = activity.subGroupOfImage(activity.mGruopMap)
                    if (activity.list == null) {
                        return;
                    }
                    activity.mGroupGridView.setAdapter(new GroupAdapter(activity, activity.list, activity.mGroupGridView));
                    break;
            }
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.selsectphoto);
    }

WeakReference则类似于可有可无的东西。在垃圾回收器线程扫描它所管辖的内存区域的过程中,一旦发现了只具有弱引用的对象,不管当前内存空间足够与否,都会回收它的内存,说白了就是一个没那么strong要求垃圾回收器将一个对象保留在内存中。不过,由于垃圾回收器是一个优先级很低的线程,因此不一定会很快发现那些只具有弱引用的对象。

你可能感兴趣的:(android,handler,内存泄露)