Volley的引用导致内存泄漏

使用Volley的项目,leakcanary基本都会显示Activity被Volley的interface reference的信息

使用WeakReference,解决了该问题(参考stackoverflow)

private static class SListener implements Response.Listener {
    private final WeakReference activityWeakReference;
    private final WeakReference callbackWeakReference;

    public SListener(Activity activity, VolleyCallback callback) {
        activityWeakReference = new WeakReference(activity);
        callbackWeakReference = new WeakReference(callback);
    }

    @Override
    public void onResponse(JSONObject jsonObject) {
        Activity act = activityWeakReference.get();
        VolleyCallback vc = callbackWeakReference.get();
        if (act != null && vc != null) {
            LogUtil.d(TAG, act.toString() + "   " + jsonObject.toString());
            something you need to do;
            vc.onSuccess(jsonObject);
        }
    }
act与callBack均已WeakReference的形式传入Volley框架使用

你可能感兴趣的:(Android)