android学习笔记
1.Handler
功能:主要是接收子线程的数据来更新主线程(UI).接收数据的主要方式是Message对象和Runnalbe对象
描述:Handler有两个作用, (1) : 定时执行Message和Runnalbe 对象
(2): 让一个动作,在不同的线程中执行.
它安排消息,用以下方法
post(Runnable)
Causes the Runnable r to be added to the message queue. The runnable will be run on the thread to which this handler is attached.
postAtTime(Runnable,long)
postDelayed(Runnable,long)
sendEmptyMessage(int)
sendMessage(Message);
sendMessageAtTime(Message,long)
sendMessageDelayed(Message,long)
1 public class MyHandlerActivity extends Activity { 2 Button button; 3 MyHandler myHandler; 4 5 protected void onCreate(Bundle savedInstanceState) { 6 super.onCreate(savedInstanceState); 7 setContentView(R.layout.handlertest); 8 9 button = (Button) findViewById(R.id.button); 10 myHandler = new MyHandler(); 11 // 当创建一个新的Handler实例时, 它会绑定到当前线程和消息的队列中,开始分发数据 12 // Handler有两个作用, (1) : 定时执行Message和Runnalbe 对象 13 // (2): 让一个动作,在不同的线程中执行. 14 15 // 它安排消息,用以下方法 16 // post(Runnable) 17 // postAtTime(Runnable,long) 18 // postDelayed(Runnable,long) 19 // sendEmptyMessage(int) 20 // sendMessage(Message); 21 // sendMessageAtTime(Message,long) 22 // sendMessageDelayed(Message,long) 23 24 // 以上方法以 post开头的允许你处理Runnable对象 25 //sendMessage()允许你处理Message对象(Message里可以包含数据,) 26 27 MyThread m = new MyThread(); 28 new Thread(m).start(); 29 } 30 31 /** 32 * 接受消息,处理消息 ,此Handler会与当前主线程一块运行 33 * */ 34 35 class MyHandler extends Handler { 36 public MyHandler() { 37 } 38 39 public MyHandler(Looper L) { 40 super(L); 41 } 42 43 // 子类必须重写此方法,接受数据 44 @Override 45 public void handleMessage(Message msg) { 46 // TODO Auto-generated method stub 47 Log.d("MyHandler", "handleMessage......"); 48 super.handleMessage(msg); 49 // 此处可以更新UI 50 Bundle b = msg.getData(); 51 String color = b.getString("color"); 52 MyHandlerActivity.this.button.append(color); 53 54 } 55 } 56 57 class MyThread implements Runnable { 58 public void run() { 59 60 try { 61 Thread.sleep(10000); 62 } catch (InterruptedException e) { 63 // TODO Auto-generated catch block 64 e.printStackTrace(); 65 } 66 67 Log.d("thread.......", "mThread........"); 68 Message msg = new Message(); 69 Bundle b = new Bundle();// 存放数据 70 b.putString("color", "我的"); 71 msg.setData(b); 72 73 MyHandlerActivity.this.myHandler.sendMessage(msg); // 向Handler发送消息,更新UI 74 75 } 76 } 77 78 }
posted on 2014-07-28 11:11 hardy_Wang 阅读(374) 评论(0) 编辑 收藏 举报