Android 启动优化(六)- 深入理解布局优化,价值2000元的学习资源泄露

渐进式加载

===================================================================

什么是渐进式加载


渐进式加载,简单来说,就是一部分一部分加载,当前帧加载完成之后,再去加载下一帧。

一种极致的做法是,加载 xml 文件,就想加载一个空白的 xml,布局全部使用 ViewStub 标签进行懒加载。

这样设计的好处是可以减缓同一时刻,加载 View 带来的压力,通常的做法是我们先加载核心部分的 View,再逐步去加载其他 View。

有人可能会这样问了,这样的设计很鸡肋,有什么用呢?

确实,在高端机上面作用不明显,甚至可能看不出来,但是在中低端机上面,带来的效果还是很明显的。在我们项目当中,复杂的页面首帧耗时约可以减少 30%。

优点:适配成本低,在中低端机上面效果明显。

缺点:还是需要在主线程读取 xml 文件

核心伪代码


start(){

loadA(){

loadB(){

loadC()

}

}

}

上面的这种写法,是可以的,但是这种做法,有一个很明显的缺点,就是会造成回调嵌套层数过多。当然,我们也可以使用 RxJava 来解决这种问题。但是,如果项目中没用 Rxjava,引用进来,会造成包 size 增加。

一个简单的做法就是使用队列的思想,将所有的 ViewStubTask 添加到队列当中,当当前的 ViewStubTask 加载完成,才加载下一个,这样可以避免回调嵌套层数过多的问题。

改造之后的代码见

val decorView = this.window.decorView

ViewStubTaskManager.instance(decorView)

.addTask(ViewStubTaskContent(decorView))

.addTask(ViewStubTaskTitle(decorView))

.addTask(ViewStubTaskBottom(decorView))

.start()

class ViewStubTaskManager private constructor(val decorView: View) : Runnable {

private var iViewStubTask: IViewStubTask? = null

companion object {

const val TAG = “ViewStubTaskManager”

@JvmStatic

fun instance(decorView: View): ViewStubTaskManager {

return ViewStubTaskManager(decorView)

}

}

private val queue: MutableList = CopyOnWriteArrayList()

private val list: MutableList = CopyOnWriteArrayList()

fun setCallBack(iViewStubTask: IViewStubTask?): ViewStubTaskManager {

this.iViewStubTask = iViewStubTask

return this

}

fun addTask(viewStubTasks: List): ViewStubTaskManager {

queue.addAll(viewStubTasks)

list.addAll(viewStubTasks)

return this

}

fun addTask(viewStubTask: ViewStubTask): ViewStubTaskManager {

queue.add(viewStubTask)

list.add(viewStubTask)

return this

}

fun start() {

if (isEmpty()) {

return

}

iViewStubTask?.beforeTaskExecute()

// 指定 decorView 绘制下一帧的时候会回调里面的 runnable

ViewCompat.postOnAnimation(decorView, this)

}

fun stop() {

queue.clear()

list.clear()

decorView.removeCallbacks(null)

}

private fun isEmpty() = queue.isEmpty() || queue.size == 0

override fun run() {

if (!isEmpty()) {

// 当队列不为空的时候,先加载当前 viewStubTask

val viewStubTask = queue.removeAt(0)

viewStubTask.inflate()

iViewStubTask?.onTaskExecute(viewStubTask)

// 加载完成之后,再 postOnAnimation 加载下一个

ViewCompat.postOnAnimation(decorView, this)

} else {

iViewStubTask?.afterTaskExecute()

}

}

fun notifyOnDetach() {

list.forEach {

it.onDetach()

}

list.clear()

}

fun notifyOnDataReady() {

list.forEach {

it.onDataReady()

}

}

}

interface IViewStubTask {

fun beforeTaskExecute()

fun onTaskExecute(viewStubTask: ViewStubTask)

fun afterTaskExecute()

}

源码地址:github.com/gdutxiaoxu/… ViewStubTaskViewStubTaskManager**, 有兴趣的可以看看

异步加载

==================================================================

异步加载,简单来说,就是在子线程创建 View。在实际应用中,我们通常会先预加载 View,常用的方案有:

  1. 在合适的时候,启动子线程 inflate layout。然后取的时候,直接去缓存里面查找 View 是否已经创建好了,是的话,直接使用缓存。否则,等待子线程 inlfate 完成。

AsyncLayoutInflater


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

  1. 每次都要现场new一个出来

  2. 异步加载的view只能通过callback回调才能获得(死穴)

因此,我们可以仿造官方的 AsyncLayoutInflater 进行改造。核心代码在 AsyncInflateManager。主要介绍两个方法。

asyncInflate 方法,在子线程 inflateView,并将加载结果存放到 mInflateMap 里面。

@UiThread

fun asyncInflate(

context: Context,

vararg items: AsyncInflateItem?

) {

items.forEach { item ->

if (item == null || item.layoutResId == 0 || mInflateMap.containsKey(item.inflateKey) || item.isCancelled() || item.isInflating()) {

return

}

mInflateMap[item.inflateKey] = item

onAsyncInflateReady(item)

inflateWithThreadPool(context, item)

}

}

getInflatedView 方法,用来获得异步inflate出来的view,核心思想如下

  • 先从缓存结果里面拿 View,拿到了view直接返回

  • 没拿到view,但是子线程在inflate中,等待返回

  • 如果还没开始inflate,由UI线程进行inflate

/**

  • 用来获得异步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

*/

@U

《Android学习笔记总结+最新移动架构视频+大厂安卓面试真题+项目实战源码讲义》

【docs.qq.com/doc/DSkNLaERkbnFoS0ZF】 完整内容开源分享

iThread

fun getInflatedView(

context: Context?,

layoutResId: Int,

parent: ViewGroup?,

inflateKey: String?,

inflater: LayoutInflater

): View {

if (!TextUtils.isEmpty(inflateKey) && mInflateMap.containsKey(inflateKey)) {

val item = mInflateMap[inflateKey]

val latch = mInflateLatchMap[inflateKey]

if (item != null) {

val resultView = item.inflatedView

if (resultView != null) {

//拿到了view直接返回

removeInflateKey(item)

replaceContextForView(resultView, context)

Log.i(TAG, “getInflatedView from cache: inflateKey is $inflateKey”)

return resultView

}

if (item.isInflating() && latch != null) {

//没拿到view,但是在inflate中,等待返回

try {

latch.await()

} catch (e: InterruptedException) {

Log.e(TAG, e.message, e)

}

removeInflateKey(item)

if (resultView != null) {

Log.i(TAG, “getInflatedView from OtherThread: inflateKey is $inflateKey”)

replaceContextForView(resultView, context)

return resultView

}

}

//如果还没开始inflate,则设置为false,UI线程进行inflate

item.setCancelled(true)

}

}

Log.i(TAG, “getInflatedView from UI: inflateKey is $inflateKey”)

//拿异步inflate的View失败,UI线程inflate

return inflater.inflate(layoutResId, parent, false)

}

简单 Demo 示范


第一步:选择在合适的时机调用 AsyncUtils#asyncInflate 方法预加载 View,

object AsyncUtils {

fun asyncInflate(context: Context) {

val asyncInflateItem =

AsyncInflateItem(

LAUNCH_FRAGMENT_MAIN,

R.layout.fragment_asny,

null,

null

)

AsyncInflateManager.instance.asyncInflate(context, asyncInflateItem)

}

fun isHomeFragmentOpen() =

getSP(“async_config”).getBoolean(“home_fragment_switch”, true)

}

第二步:在获取 View 的时候,先去缓存里面查找 View

override fun onCreateView(

inflater: LayoutInflater, container: ViewGroup?,

savedInstanceState: Bundle?

): View? {

// Inflate the layout for this fragment

val startTime = System.currentTimeMillis()

val homeFragmentOpen = AsyncUtils.isHomeFragmentOpen()

val inflatedView: View

inflatedView = AsyncInflateManager.instance.getInflatedView(

context,

R.layout.fragment_asny,

container,

LAUNCH_FRAGMENT_MAIN,

inflater

)

Log.i(

TAG,

“onCreateView: homeFragmentOpen is $homeFragmentOpen, timeInstance is ${System.currentTimeMillis() - startTime}, ${inflatedView.context}”

)

return inflatedView

// return inflater.inflate(R.layout.fragment_asny, container, false)

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值