Android Handler

 1 package com.example.myapp7;
 2 
 3 import android.support.v7.app.ActionBarActivity;
 4 import android.os.Bundle;
 5 import android.os.Handler;
 6 import android.os.Looper;
 7 import android.os.Message;
 8 import android.util.Log;
 9 import android.view.Menu;
10 import android.view.MenuItem;
11 import android.view.View;
12 import android.widget.Button;
13 /**
14  * UI线程发送数据,子线程接收数据。
15  * @author shaobn
16  * @date 2015-9-15
17  * @packege com.example.myapp7MyApp7
18  */
19 public class MainActivity extends ActionBarActivity {
20     private Button button;
21     private Handler handler;
22     @Override
23     protected void onCreate(Bundle savedInstanceState) {
24         super.onCreate(savedInstanceState);
25         setContentView(R.layout.activity_main);
26         button = (Button) this.findViewById(R.id.button1);
27         button.setOnClickListener(new View.OnClickListener() {
28             
29             @Override
30             public void onClick(View arg0) {
31                 // TODO Auto-generated method stub
32                 Message message = handler.obtainMessage();
33                 message.what = 8;
34                 handler.sendMessage(message);
35             }
36         });
37         MyThread myThread = new MyThread();
38         Thread thread = new Thread(myThread);
39         thread.start();
40     }
41     class MyThread implements Runnable{
42         @Override
43         public void run() {
44             // TODO Auto-generated method stub
45             Looper.prepare();
46             handler = new Handler(){
47                 @Override
48                 public void handleMessage(Message msg) {
49                     // TODO Auto-generated method stub
50                     Log.i("msg","--->>>"+String.valueOf(msg.what));
51                 }
52             };
53             Looper.loop();
54         }
55         
56     }
57 }

 

posted @ 2015-09-15 22:30  邻家小书童  阅读(130)  评论(0编辑  收藏  举报