美文网首页
探究为什么Glide 可以与 Activity 生命周期绑定

探究为什么Glide 可以与 Activity 生命周期绑定

作者: JokAr_ | 来源:发表于2018-11-22 14:32 被阅读25次

    用过Glide同学都知道,Glide的最大不同之处就是可以与Activity 生命周期绑定,在Activity onDestroy时自动结束网络请求,释放资源。
    那么为什么Glide 可以做到与Activity绑定生命周期,并且是怎么做到到呢?
    我们通过一些代码来说明(代码均来自Glide源码):

    首先我们创建一个 LifeCycleListener

    public interface LifeCycleListener {
        /**
         * Callback for when {@link android.app.Fragment#onStart()}} or {@link
         * android.app.Activity#onStart()} is called.
         */
        void onStart();
    
        /**
         * Callback for when {@link android.app.Fragment#onStop()}} or {@link
         * android.app.Activity#onStop()}} is called.
         */
        void onStop();
    
        /**
         * Callback for when {@link android.app.Fragment#onDestroy()}} or {@link
         * android.app.Activity#onDestroy()} is called.
         */
        void onDestroy();
    }
    
    

    创建 LifeCycleListener 管理类

    public class ActivityFragmentLifeCycle {
        private LifeCycleListener lifecycleListener;
    
        public void addListener(@NonNull LifeCycleListener listener) {
            lifecycleListener = listener;
        }
    
        void onStart() {
            if (lifecycleListener != null)
                lifecycleListener.onStart();
    
        }
    
        void onStop() {
            if (lifecycleListener != null)
                lifecycleListener.onStop();
    
        }
    
        void onDestroy() {
            if (lifecycleListener != null)
                lifecycleListener.onDestroy();
        }
    }
    
    

    创建一个操作ActivityFragmentLifeCycleFragment

    public class SupportManagerFragment extends Fragment {
        private ActivityFragmentLifeCycle lifecycle;
        public SupportManagerFragment() {
            this(new ActivityFragmentLifeCycle());
        }
    
        @SuppressLint("ValidFragment")
        public SupportManagerFragment(@NonNull ActivityFragmentLifeCycle lifeCycle) {
            this.lifecycle = lifeCycle;
        }
    
        @NonNull
        ActivityFragmentLifeCycle getLifeCycle() {
            return lifecycle;
        }
    
    
        @Override
        public void onStart() {
            super.onStart();
            lifecycle.onStart();
        }
    
        @Override
        public void onStop() {
            super.onStop();
            lifecycle.onStop();
        }
    
        @Override
        public void onDestroy() {
            super.onDestroy();
            lifecycle.onDestroy();
        }
    }
    
    

    这里就是关键类了,为什么要有个Fragment?因为他绑定Activity生命周期的方式就是给当前Activity加上Fragment通过这个Fragment 来管理生命周期。
    下面就介绍如何创建Fragment依托于当前的Activity获得生命周期管理

    获得Activity ,来创建Fragment管理生命周期

    /**
     * Create by JokAr. on 2018/12/24.
     */
    public class RequestManager implements LifeCycleListener {
    
        private static final String TAG = RequestManager.class.getSimpleName();
    
        /**
         * 绑定activity
         * @param context 传入的上下文
         */
        public void bind(Context context) {
            if (context == null) {
                throw new IllegalArgumentException("You cannot start a load on a null Context");
            } else if (Util.isOnMainThread() && !(context instanceof Application)) {
                if (context instanceof FragmentActivity) {
                    bind((FragmentActivity) context);
                } else if (context instanceof Activity) {
                    bind((AppCompatActivity) context);
                } else if (context instanceof ContextWrapper) {
                    bind(((ContextWrapper) context).getBaseContext());
                }
            }
        }
    
        
        private void bind(AppCompatActivity activity) {
            FragmentManager fragmentManager = activity.getSupportFragmentManager();
            supportFragmentGet(fragmentManager, isActivityVisible(activity));
        }
    
        private void bind(FragmentActivity activity) {
            FragmentManager fragmentManager = activity.getSupportFragmentManager();
            supportFragmentGet(fragmentManager, isActivityVisible(activity));
        }
    
        /**
         * 创建Fragment 并依托于当前Activity(当然Glide做了缓存去重操作) 
         * @param fragmentManager
         * @param activityVisible
         */
        private void supportFragmentGet(FragmentManager fragmentManager, boolean activityVisible) {
            SupportManagerFragment current = new SupportManagerFragment();
    
            fragmentManager.beginTransaction()
                    .add(current, "managerLife")
                    .commitAllowingStateLoss();
            current.getLifeCycle().addListener(this);
            if (activityVisible) {
                current.getLifeCycle().onStart();
            }
        }
    
        private boolean isActivityVisible(Activity activity) {
            return !activity.isFinishing();
        }
    
        @Override
        public void onStart() {
            //do you buzz
            Log.i(TAG, "onStart: ");
        }
    
        /**
         * 当出现该函数时,可以暂停Glide网络图片的请求
         */
        @Override
        public void onStop() {
            //do you buzz
            Log.i(TAG, "onStop: ");
        }
    
        @Override
        public void onDestroy() {
            //do you buzz
            Log.i(TAG, "onDestroy: ");
        }
    }
    
    

    调用

    RequestManager requestManager = new RequestManager();
    requestManager.bind(this);
    

    通过这样,我们就可以自己实现绑定Activity生命周期管理,也知道了Glide 是怎样绑定的

    相关文章

      网友评论

          本文标题:探究为什么Glide 可以与 Activity 生命周期绑定

          本文链接:https://www.haomeiwen.com/subject/znavaftx.html