Android:线程间通讯的其他方法、runOnUiThread(action)、Handler.post(action)、post

本文摘要:






1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51......

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 public class MainActivity extends Activity implements OnClickListener {     TextView textView = null;     private View mProgress;             private Handler mHandler = new Handler();     @Override     protected void onCreate(Bundle savedInstanceState)     {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);                     findViewById(R.id.button1).setOnClickListener(this);         findViewById(R.id.button2).setOnClickListener(this);         textView = (TextView) findViewById(R.id.textView1);         mProgress = findViewById(R.id.progressBar1);     }             @Override     public boolean onCreateOptionsMenu(Menu menu)     {         getMenuInflater().inflate(R.menu.activity_main, menu);         return true;     }             @Override     public void onClick(View v)     {         switch (v.getId())         {         case R.id.button1:             btn1Click();             break;         default:             break;         }     }                        private void btn1Click()     {         mProgress.setVisibility(View.VISIBLE);         new Thread()         {             @Override             public void run()             {                 final String str = update();                 Runnable action = new Runnable()//该方法仍然是在main线程中完成的                 {                     @Override                     public void run()//run里进行main线程的事件                     {                        textView.setText(str);                        mProgress.setVisibility(View.GONE);                        Log.e("runnable", Thread.currentThread().getName());                     }                 };                 /*                  * 除Handler外的其他三种方法,适用于控件较少的场景                  */                 runOnUiThread(action);//方法一                 textView.post(action);//方法二,post方法执行前会调用                 mHandler.post(action);//方法三                 mHandler.postDelayed(action, 3000);//方法三可以加个延时             }         }.start();     }                     private String update()     {         return "更新完成!";     }         }


注:

1.handler.post这个函数的作用是把Runnable里面的run方法里面的这段代码发送到消息队列中,等待运行。
如果handler是以UI线程消息队列为参数构造的,那么是把run里面的代码发送到UI线程中,等待UI线程运行这段代码。
如果handler是以子线程线程消息队列为参数构造的,那么是把run里面的代码发送到子线程中,等待子线程运行这段代码。






本文转自 glblong 51CTO博客,原文链接:http://blog.51cto.com/glblong/1206265,如需转载请自行联系原作者

标签