Android异步更新UI的方式之使用Handler消息传递机制
16lz
2021-01-26
由于性能要求,android要求只能在UI线程中更新UI,要想在其他线程中更新UI,给大家介绍一种方式:使用Handler消息传递机制。
下面用这种方式更新一个TextView:
packagecom.example.runonuithreadtest;importandroid.app.Activity;importandroid.os.Bundle;importandroid.os.Handler;importandroid.widget.TextView;publicclassMainActivityextendsActivity{privateTextViewtv;Handlerhandler=newHandler(){publicvoidhandleMessage(android.os.Messagemsg){if(msg.what==0x123){tv.setText("更新后的TextView");}};};@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);tv=(TextView)findViewById(R.id.tv);newMyThread().start();}classMyThreadextendsThread{@Overridepublicvoidrun(){//延迟两秒更新try{Thread.sleep(2000);}catch(InterruptedExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}handler.sendEmptyMessage(0x123);}}}
当然对APP的性能测试,我比较常用的是这个平台:www.ineice.com
更多相关文章
- Android(安卓)Thread第二次Thread.start()报错的疑问
- Android异步更新UI的方式之使用Handler的post(Runnabel r)方法
- Android(安卓)TextView实现下划线的几种方式
- this version of ADT requires android SDK tools revision 21.0
- 学习笔记:Android开源库使用方法总结
- Java(Android)数据结构汇总(二)-- Set(下)
- android 更新UI的两种方法
- android的两种启动service方式及混合方式
- android 在surfaceView上画图