一、主线程申请成功后子线程申请
val textView:TextView = findViewById<TextView>(R.id.textView)
textView.setOnClickListener{
textView.text = "Main"
thread{
textView.text = "${Thread.currentThread().name}"
}
}
二、在子线程中创建ViewRootImpl
thread{
Looper.prepare()
val button = Button(this)
windowManager.addView(button,WindowManager.LayoutParams())
button.setOnClickListener{
button.text="${Thread.currentThread().name}"
}
Looper.loop()
}
三、利用硬件加速机制绕开requestLayout()
在硬件加速支持下,如果控件只是执行了invalidate(),而没有触发requestLayout(),是不会触发ViewRootImpl#checkThread()的
ViewGroup.png
四、SurfaceView
Android中有一个控件SurfaceView,可以通过holder获得Canvas对象,可以直接在子线程中更新UI
val surface :SurfaceView! =findViewById<SurfaceView>(R.id.surface)
surface.holder.addCallback(object :SurfaceHolder.Callback {
override fun surfacedreated(holder:SurfaceHolder){
thread {
while(!destroved){
val canvas :Canvas! = holder.lockCanvas()
val random = Random()
val r:Int =random.nextInt( bound: 255)
val g:Int =random.nextInt( bound: 255)
val b:Int = random.nextInt( bound: 255)
canvas.drawColor(Color.rgb(r,g,b))
holder.unlockCanvasAndPost(canvas)
SystemClock.sleep( ms:500)
}
}
}
override fun surfaceDestroyed(holder: SurfaceHolder?){
destroved = true
}
override fun surfaceChanged(
holder: SurfaceHolder?,
format: Int
width: Int
height: Int
){
}
}