Glide生命周期管理

来源:互联网 发布:misumi软件 编辑:程序博客网 时间:2024/06/05 15:51

Glide.with里面有这段代码

public RequestManager get(Activity activity) {        if (Util.isOnBackgroundThread()) {            return get(activity.getApplicationContext());        } else {            assertNotDestroyed(activity);            android.app.FragmentManager fm = activity.getFragmentManager();            return fragmentGet(activity, fm, null /*parentHint*/);        }    }    public RequestManager get(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) {                return get((FragmentActivity) context);            } else if (context instanceof Activity) {                return get((Activity) context);            } else if (context instanceof ContextWrapper) {                return get(((ContextWrapper) context).getBaseContext());            }        }        return getApplicationManager(context);    }

如果是子线程

private RequestManager getApplicationManager(Context context) {        ......        applicationManager = factory.build(glide, new ApplicationLifecycle(), new EmptyRequestManagerTreeNode());//------主要这句        ......        return applicationManager;    }

ApplicationLifecycle里面就调用了onStart方法,也就是子线程无法进行生命周期管理

class ApplicationLifecycle implements Lifecycle {  @Override  public void addListener(LifecycleListener listener) {    listener.onStart();  }  @Override  public void removeListener(LifecycleListener listener) {    // Do nothing.  }}

然后再看,是主线程的情况

private RequestManager fragmentGet(Context context, android.app.FragmentManager fm,                                       android.app.Fragment parentHint) {        RequestManagerFragment current = getRequestManagerFragment(fm, parentHint);        RequestManager requestManager = current.getRequestManager();        if (requestManager == null) {            Glide glide = Glide.get(context);            requestManager =                    factory.build(glide, current.getLifecycle(), current.getRequestManagerTreeNode());            current.setRequestManager(requestManager);        }        return requestManager;    }

getRequestManagerFragment会自动生成空白fragment,里面有ActivityFragmentLifecycle
这是ActivityFragmentLifecycle种的部分实现

  @Override  public void addListener(LifecycleListener listener) {    lifecycleListeners.add(listener);    if (isDestroyed) {      listener.onDestroy();    } else if (isStarted) {      listener.onStart();    } else {      listener.onStop();    }  }

那又是如何调用的呢?
就在fragmentGet函数里面的factory.build里面。这是个借口,具体实现就是new RequestManager。里面有这样一段代码

if (Util.isOnBackgroundThread()) {            mainHandler.post(addSelfToLifecycle);        } else {            lifecycle.addListener(this);//这样就算是这是开启生命周期管理        }

总结:其实with就是用来进行生命周期管理的(不能写在子线程中,不然不会管理)