1.说明
安卓中UI线程为主线程,更新UI界面必须在主线程中进行,在子线程中实现更新UI界面的三种方法:Handler、RunOnUiThread、控件.post()
2.1 Handler
(1)定义handler
private Handler handler=new Handler(new Handler.Callback() {@Overridepublic boolean handleMessage(@NonNull Message message) {switch (message.what){case 0:String S=(String)msg.obj;Btn.setText(S);break;case 1:break;default:break;}return false;}});
(2)使用
Message msg=new Message();msg.what=0;msg.obj="Finish";//此处也可以传递对象handler.sendMessage(msg);<2>RunOnUiThreadrunOnUiThread(new Runnable() {@Overridepublic void run() {//doSomething;}});
2.2 控件.post()
TextView.post(new Runnable() {@Overridepublic void run() {TextView.setText("Fi");}});}
2.3 在子线程中使用 runOnUiThread
runOnUiThread(new Runnable() {@Overridepublic void run() {//doSomething...}});