Android - 一种新奇的冷启动速度优化思路(Fragment极度懒加载 + Layout子线程预加载)

if (!hasReplacedAllEmptyFragments && mCurrentSelectedTab != mDefaultTab && state == 0) {
//当满足: 1. 没有全部替换完 2. 当前tab不是初始化的默认tab(默认tab不会用空的Fragment去替换) 3. 滑动结束了,即state = 0
replaceEmptyFragmentsIfNeed(mCurrentSelectedTab);
}
}

备注:

onPageScrollStateChanged接滑动的状态值。一共有三个取值:

0:什么都没做
1:开始滑动
2:滑动结束

一次引起页面切换的滑动,state的顺序分别是: 1  ->  2  ->  0

2)进行Fragment的替换,这里因为我们的tab数量是可能根据全局config信息而改变的,所以这个地方写的稍微纠结了一些。

/**

  • 如果全部替换完了,直接return
  • 替换过程:
    1. 找到当前空的tab在mEmptyFragmentList 中的实际下标
  • @param tabId 要替换的tab的tabId - (当前空的Fragment在adapter数据列表mFragmentList的下标)
    */
    private void replaceEmptyFragmentsIfNeed(int tabId) {
    if (hasReplacedAllEmptyFragments) {
    return;
    }
    int tabRealIndex = mEmptyFragmentList.indexOf(mFragmentList.get(tabId)); //找到当前的空Fragment在 mEmptyFragmentList 是第几个
    if (tabRealIndex > -1) {
    if (Collections.replaceAll(mFragmentList, mEmptyFragmentList.get(tabRealIndex), mDataFragmentList.get(tabRealIndex))) {
    mTabsAdapter.refreshFragments(mFragmentList); //将mFragmentList中的相应empty fragment替换完成之后刷新数据
    boolean hasAllReplaced = true;
    for (Fragment fragment : mFragmentList) {
    if (fragment instanceof EmptyPlaceHolderFragment) {
    hasAllReplaced = false;
    break;
    }
    }
    if (hasAllReplaced) {
    mEmptyFragmentList.clear(); //全部替换完成的话,释放引用
    }
    hasReplacedAllEmptyFragments = hasAllReplaced;
    }
    }
    }

六、神奇的的预加载(预加载View,而不是data)

Android在启动过程中可能涉及到的一些View的预加载方案:

  1. WebView提前创建好,因为webview创建的耗时较长,如果首屏有h5的页面,可以提前创建好。
  2. Application的onCreate时,就可以开始在子线程中进行后面要用到的Layout的inflate工作了,最先想到的应该是官方提供的AsyncLayoutInflater
  3. 填充View的数据的预加载,今天的内容不涉及这一项

6.1 需要预加载什么

直接看图,这个是首页四个子Tab Fragment的基类的layout,因为某些东西设计的不合理,导致层级是非常的深,直接导致了首页上的三个tab加上FeedMainFragment自身,光将这个View inflate出来的时间就非常长。因此我们考虑在子线程中提前inflate layout

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

6.2 修改AsyncLayoutInflater

官方提供了一个类,可以来进行异步的inflate,但是有两个缺点:

  1. 每次都要现场new一个出来
  2. 异步加载的view只能通过callback回调才能获得(死穴)

因此决定自己封装一个AsyncInflateManager,内部使用线程池,且对于inflate完成的View有一套缓存机制。而其中最核心的LayoutInflater则直接copy出来就好。

先看AsyncInflateManager的实现,这里我直接将代码copy进来,而不是截图了,这样你们如果想用其中部分东西,可以直接copy:

/**

  • @author zoutao
  • 用来提供子线程inflate view的功能,避免某个view层级太深太复杂,主线程inflate会耗时很长,
  • 实就是对 AsyncLayoutInflater进行了抽取和封装
    */
    public class AsyncInflateManager {
    private static AsyncInflateManager sInstance;
    private ConcurrentHashMap<String, AsyncInflateItem> mInflateMap; //保存inflateKey以及InflateItem,里面包含所有要进行inflate的任务
    private ConcurrentHashMap<String, CountDownLatch> mInflateLatchMap;
    private ExecutorService mThreadPool; //用来进行inflate工作的线程池

private AsyncInflateManager() {
mThreadPool = new ThreadPoolExecutor(4, 4, 0, TimeUnit.MILLISECONDS, new LinkedBlockingDeque());
mInflateMap = new ConcurrentHashMap<>();
mInflateLatchMap = new ConcurrentHashMap<>();
}

public static AsyncInflateManager getInstance() {
单例
}

/**

  • 用来获得异步inflate出来的view
  • @param context
  • @param layoutResId 需要拿的layoutId
  • @param parent container
  • @param inflateKey 每一个View会对应一个inflateKey,因为可能许多地方用的同一个 layout,但是需要inflate多个,用InflateKey进行区分
  • @param inflater 外部传进来的inflater,外面如果有inflater,传进来,用来进行可能的SyncInflate,
  • @return 最后inflate出来的view
    */
    @UiThread
    @NonNull
    public View getInflatedView(Context context, int layoutResId, @Nullable ViewGroup parent, String inflateKey, @NonNull LayoutInflater inflater) {
    if (!TextUtils.isEmpty(inflateKey) && mInflateMap.containsKey(inflateKey)) {
    AsyncInflateItem item = mInflateMap.get(inflateKey);
    CountDownLatch latch = mInflateLatchMap.get(inflateKey);
    if (item != null) {
    View resultView = item.inflatedView;
    if (resultView != null) {
    //拿到了view直接返回
    removeInflateKey(inflateKey);
    replaceContextForView(resultView, context);
    return resultView;
    }

if (item.isInflating() && latch != null) {
//没拿到view,但是在inflate中,等待返回
try {
latch.wait();
} catch (InterruptedException e) {
Log.e(TAG, e.getMessage(), e);
}
removeInflateKey(inflateKey);
if (resultView != null) {
replaceContextForView(resultView, context);
return resultView;
}

}
//如果还没开始inflate,则设置为false,UI线程进行inflate
item.setCancelled(true);
}
}
//拿异步inflate的View失败,UI线程inflate
return inflater.inflate(layoutResId, parent, false);
}

/**

  • inflater初始化时是传进来的application,inflate出来的view的context没法用来startActivity,
  • 因此用MutableContextWrapper进行包装,后续进行替换
    */
    private void replaceContextForView(View inflatedView, Context context) {
    if (inflatedView == null || context == null) {
    return;
    }
    Context cxt = inflatedView.getContext();
    if (cxt instanceof MutableContextWrapper) {
    ((MutableContextWrapper) cxt).setBaseContext(context);
    }
    }

@UiThread
private void asyncInflate(Context context, AsyncInflateItem item) {
if (item == null || item.layoutResId == 0 || mInflateMap.containsKey(item.inflateKey) || item.isCancelled() || item.isInflating()) {
return;
}
onAsyncInflateReady(item);
inflateWithThreadPool(context, item);
}

private void onAsyncInflateReady(AsyncInflateItem item) {

}

private void onAsyncInflateStart(AsyncInflateItem item) {

}

private void onAsyncInflateEnd(AsyncInflateItem item, boolean success) {
item.setInflating(false);
CountDownLatch latch = mInflateLatchMap.get(item.inflateKey);
if (latch != null) {
//释放锁
latch.countDown();
}

}

private void removeInflateKey(String inflateKey) {

}

private void inflateWithThreadPool(Context context, AsyncInflateItem item) {
mThreadPool.execute(new Runnable() {
@Override
public void run() {
if (!item.isInflating() && !item.isCancelled()) {
try {
onAsyncInflateStart(item);
item.inflatedView = new BasicInflater(context).inflate(item.layoutResId, item.parent, false);
onAsyncInflateEnd(item, true);
} catch (RuntimeException e) {
Log.e(TAG, “Failed to inflate resource in the background! Retrying on the UI thread”, e);
onAsyncInflateEnd(item, false);
}
}
}
});
}

/**

  • copy from AsyncLayoutInflater - actual inflater
    */
    private static class BasicInflater extends LayoutInflater {
    private static final String[] sClassPrefixList = new String[]{“android.widget.”, “android.webkit.”, “android.app.”};

BasicInflater(Context context) {
super(context);
}

public LayoutInflater cloneInContext(Context newContext) {
return new BasicInflater(newContext);
}

protected View onCreateView(String name, AttributeSet attrs) throws ClassNotFoundException {
for (String prefix : sClassPrefixList) {
try {
View view = this.createView(name, prefix, attrs);
if (view != null) {
return view;
}
} catch (ClassNotFoundException ignored) {
}
}
return super.onCreateView(name, attrs);
}
}
}

这里我用一个AsyncInflateItem来管理一次要inflate的一个单位,

/**

  • @author zoutao
    */
    public class AsyncInflateItem {
    String inflateKey;
    int layoutResId;
    ViewGroup parent;
    OnInflateFinishedCallback callback;
    View inflatedView;

private boolean cancelled;
private boolean inflating;

//还有一些set get方法
}

以及最后inflate的回调callback:

public interface OnInflateFinishedCallback {
void onInflateFinished(AsyncInflateItem result);
}

经过这样的封装,外面可以直接在Application的onCreate中,开始异步的inflate view的任务。调用如下:

AsyncInflateUtil.startTask();

/**

  • @author zoutao
    */
    public class AsyncInflateUtil {
    public static void startTask() {
    Context context = new MutableContextWrapper(CommonContext.getApplication());
    AsyncInflateManager.getInstance().asyncInflateViews(context,
    new AsyncInflateItem(InflateKey.TAB_1_CONTAINER_FRAGMENT, R.layout.fragment_main),
    new AsyncInflateItem(InflateKey.SUB_TAB_1_FRAGMENT, R.layout.fragment_load_list),
    new AsyncInflateItem(InflateKey.SUB_TAB_2_FRAGMENT, R.layout.fragment_load_list),
    new AsyncInflateItem(InflateKey.SUB_TAB_3_FRAGMENT, R.layout.fragment_load_list),
    new AsyncInflateItem(InflateKey.SUB_TAB_4_FRAGMENT, R.layout.fragment_load_list));

}

public class InflateKey {
public static final String TAB_1_CONTAINER_FRAGMENT = “tab1”;
public static final String SUB_TAB_1_FRAGMENT = “sub1”;
public static final String SUB_TAB_2_FRAGMENT = “sub2”;
public static final String SUB_TAB_3_FRAGMENT = “sub3”;
public static final String SUB_TAB_4_FRAGMENT = “sub4”;
}
}

注意:这里会有一个坑。就是在Application的onCreate中,能拿到的Context只有Application,这样inflate的View,View持有的Context就是Application,这会导致一个问题。

如果用View.getContext()这个context去进行Activity的跳转就会。。抛异常

Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?

而如果想要传入Activity来创建LayoutInflater,时机又太晚。众所周知,Context是一个抽象类,实现它的包装类就是ContextWrapper,而Activity、Appcation等都是ContextWrapper的子类,然而,ContextWrapper还有一个神奇的子类,

package android.content;

/**

  • Special version of {@link ContextWrapper} that allows the base context to
  • be modified after it is initially set.
    */
    public class MutableContextWrapper extends ContextWrapper {
    public MutableContextWrapper(Context base) {
    super(base);
    }

/**

  • Change the base context for this ContextWrapper. All calls will then be
  • delegated to the base context. Unlike ContextWrapper, the base context
  • can be changed even after one is already set.
  • @param base The new base context for this wrapper.
    */
    public void setBaseContext(Context base) {
    mBase = base;
    }
    }

6.3 装饰器模式

可以看到Android上Context的设计采用了装饰器模式,装饰器模式极大程度的提高了灵活性。这个例子对我最大的感受就是,当官方没有提供MutableContextWrapper这个类时,其实我们自己也完全可以通过同样的方式去进行实现。思维一定要灵活~

七、总结

常见的启动速度优化的方案有:

  • 数据懒加载,比如Fragment用户不可见时不进行数据的获取
  • 优化布局层级,减少首次inflate layout的耗时
  • 将绝大部分sdk的初始化放线程池中运行

总结

找工作是个很辛苦的事情,而且一般周期都比较长,有时候既看个人技术,也看运气。第一次找工作,最后的结果虽然不尽如人意,不过收获远比offer大。接下来就是针对自己的不足,好好努力了。

最后为了节约大家的时间,我把我学习所用的资料和面试遇到的问题和答案都整理成了PDF文档

喜欢文章的话请关注、点赞、转发 谢谢!

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化学习资料的朋友,可以戳这里获取

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

就是针对自己的不足,好好努力了。

最后为了节约大家的时间,我把我学习所用的资料和面试遇到的问题和答案都整理成了PDF文档

喜欢文章的话请关注、点赞、转发 谢谢!

[外链图片转存中…(img-gmtLTR4I-1714261160979)]

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化学习资料的朋友,可以戳这里获取

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

  • 8
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值