Sub Thread to update main Thread (UI)
main Thread : A has Hander.HandleMessage() to process the "Msg" from subthread B;
Sub Thread : B use Hander.sendMessage(Msg) to main Thread A;
1 import java.util.Timer; 2 import java.util.TimerTask; 3 import android.app.Activity; 4 import android.os.Bundle; 5 import android.os.Handler; 6 import android.os.Message; 7 public class HandlerDemo extends Activity { 8 9 //title为setTitle方法提供变量,这里为了方便我设置成了int型 10 private int title = 0; 11 private Handler mHandler = new Handler(){ 12 public void handleMessage(Message msg) { 13 switch (msg.what) { 14 case 1: 15 updateTitle(); 16 break; 17 } 18 }; 19 }; 20 public void onCreate(Bundle savedInstanceState) { 21 super.onCreate(savedInstanceState); 22 setContentView(R.layout.main); 23 24 Timer timer = new Timer(); 25 timer.scheduleAtFixedRate(new MyTask(), 1, 5000); 26 } 27 28 private class MyTask extends TimerTask{ 29 @Override 30 public void run() { 31 //处理事情 32 Message message = new Message(); 33 message.what = 1; 34 mHandler.sendMessage(message); 35 36 } 37 } 38 39 40 public void updateTitle(){ 41 42 setTitle("Welcome to Mr Wei‘s blog " + title); 43 title ++; 44 } 45 }
时间: 2024-10-14 10:07:04