首页 > 代码库 > Sub Thread to update main Thread (UI)
Sub Thread to update main Thread (UI)
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 }
Sub Thread to update main Thread (UI)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。