1.handler.send(Message message),或者handler.post (Runnable r);
2.View.post(Runnable r);
- /**
- * 更新UI方法之 view.post(Runnable r)
- * @author vincentTung
- *
- */
- class ViewPostThread extends Thread{
- @Override
- public void run() {
- super.run();
- while(count<101){
- /**
- * view.post(Runnable)
- */
- bar.post(new Runnable() {
- @Override
- public void run() {
- isChanging = true;
- bar.setProgress(count);
- count++;
- }});
- /**
- * view.postDelayed(Runnable,delayTime)
- */
- // bar.postDelayed(new Runnable() {
- //
- // @Override
- // public void run() {
- // isChanging = true;
- // bar.setProgress(count);
- // count++;
- //
- // }},100);
- //
- try {
- Thread.sleep(100);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- }
3.Activity的RunOnUIThread(Runnable r);
- class ViewPostThread extends Thread{
- @Override
- public void run() {
- super.run();
- while(count<101){
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- isChanging = true;
- bar.setProgress(count);
- count++;
- }});
- try {
- Thread.sleep(100);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- }
4.通过HandlerThread进行更新
- /**
- *
- *
- * 更新UI方法之
- * ---- HandlerThread
- *
- * HandlerThread与普通Thread的区别是,普通Thread 默认不带Looper的,
- * 需要调用Looper.prepare()方法为线程分配出有一个Looper,然后通过Looper.loop()方法让Looper转起来,循环分发消息Message
- * 而HandlerThread就可以看作是默认就非配有Looper的线程Thread
- * 1.在子线程中声明Handler
- * 2.在子线程的run()方法中:Looper.prepare();//为子线程分配一个Looper
- * 3.在子线程的run()方法中:处理操作,并发送Message
- * 4.在子线程的run()方法中: Looper.loop();//让Loop转起来
- *
- * @author vincentTung
- *
- */
- private HandlerThread handlerThread =new HandlerThread("handler_thread"){
- private Handler handler = new Handler(){
- public void handleMessage(android.os.Message msg) {
- count++;
- bar.setProgress(count);
- if(count==100){
- Toast.makeText(HandlerThreadTest.this, "Done", 1).show();
- }
- };
- };
使用时候调用
handlerThread.start();
5.在子线程中更新,前提是得Loop.prepare( );
- /**
- *
- *
- * 更新UI方法之
- * ---- 带Looper的子线程
- * 1.在子线程中声明Handler
- * 2.在子线程的run()方法中:Looper.prepare();//为子线程分配一个Looper
- * 3.在子线程的run()方法中:处理操作,并发送Message
- * 4.在子线程的run()方法中: Looper.loop();//让Loop转起来
- *
- * @author vincentTung
- *
- */
- class NormalThread extends Thread{
- private int count=0;
- private Handler handler = new Handler(){
- public void handleMessage(android.os.Message msg) {
- count++;
- bar.setProgress(count);
- };};
- @Override
- public void run() {
- super.run();
- Looper.prepare();
- while(count<=100){
- handler.sendEmptyMessage(0);
- try {
- Thread.sleep(100);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- Looper.loop();
- }
- }