android中使用多线程——HandlerThread举例

android中使用多线程——HandlerThread举例
预览:

android中使用多线程——HandlerThread举例

2011-12-02 www.cxybl.com 标签: android 多线程 HandlerThread public class HandlerTest2 extends Activity{ @Override public void onCreate(BundlesavedInstanceState){ super .onCreate(savedInstanceState); setContentView(R.layout.main); System.out.println( Activity-- +Thread.currentThread().getId()+Thread

1. public class HandlerTest2 extends Activity {

2. @Override

3. public void onCreate(Bundle savedInstanceState) {

4. super.onCreate(savedInstanceState);

5. setContentView(R.layout.main);

6. System.out.println("Activity-->"+Thread.currentThread().getId()+Thread.currentThread().getName());

7. //创建一个名为ActivityHandler的线程

8. HandlerThread handlerThread = new HandlerThread("ActivityHandler");

9. //在使用handlerThread的getLooper()之前,要首先调用start()方法

10. handlerThread.start();

11. MyHandler myHandler = new MyHandler(handlerThread.getLooper());

12. Message msg = myHandler.obtainMessage();

13. Bundle bundle = new Bundle();

14. bundle.putString("name", "Mary");

15. bundle.putInt("age", 20);

16. msg.setData(bundle);

17. //将msg发送到目标对象,所谓的目标对象,就是生成该msg对象的handler对象,本例中即为myHandler

18. msg.sendToTarget();

19. }

20.}

21.class MyHandler extends Handler{

22.public MyHandler() {

23.super();

24.}

25.public MyHandler(Looper looper) {

26.super(looper);

27.}

28.@Override

29.public void handleMessage(Message msg) {

30.super.handleMessage(msg);

第1页/共2页 下一页>