Handler应用3 — 与Activity不同一线程

MainActivity:

 1 package com.example.handlerthread;
 2 
 3 import android.os.Bundle;
 4 import android.os.Handler;
 5 import android.os.HandlerThread;
 6 import android.os.Looper;
 7 import android.os.Message;
 8 import android.annotation.SuppressLint;
 9 import android.app.Activity;
10 import android.content.Intent;
11 import android.view.Menu;
12 
13 @SuppressLint("HandlerLeak")
14 public class MainActivity extends Activity {
15 
16     protected void onCreate(Bundle savedInstanceState) {
17         super.onCreate(savedInstanceState);
18         setContentView(R.layout.activity_main);
19         
20         //声明一个Handler线程
21         HandlerThread hdt = new HandlerThread("myHandlerThread");
22         //在getLooper()之前要先start线程!!!
23         hdt.start();
24         MyHandler myhandler = new MyHandler(hdt.getLooper());
25         //得到handler的Message
26         Message msg = myhandler.obtainMessage();
27 
28         //bundle用于数据打包传送
29         Bundle bundle = new Bundle();
30         bundle.putInt("age", 20);
31         bundle.putString("name", "Human");
32         bundle.putFloat("Score", 99.9f);
33         //Message的setData
34         msg.setData(bundle);
35         //把msg送到Target处(生产msg的handler处)
36         msg.sendToTarget();
37 
38     }
39 
40     class MyHandler extends Handler {
41         public MyHandler() {
42         }
43         //构造函数,参数为Looper
44         public MyHandler(Looper looper) {
45             super(looper);
46         }
47         
48         //重写父类的handleMessage方法
49         //当handler得到msg后就执行handleMessage方法
50         public void handleMessage(Message msg) {
51             Bundle bd = msg.getData();
52             int age = bd.getInt("age");
53             System.out.println(age);
54         }
55     }
56     public boolean onCreateOptionsMenu(Menu menu) {
57         // Inflate the menu; this adds items to the action bar if it is present.
58         getMenuInflater().inflate(R.menu.activity_main, menu);
59         return true;
60     }
61 }
原文地址:https://www.cnblogs.com/humanchan/p/3020845.html