android开发教程之使用looper处理消息队列

复制代码 代码如下:

package com.yanjun;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;

public class HandlerActivity extends Activity {

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
      // 通过HandlerThread对象来实现使用looper处理消息队列的功能
    HandlerThread handlerThread = new HandlerThread("handlerThread");
    // 使线程运行必须调用start()
    handlerThread.start();
    MyHandler myHandler = new MyHandler(handlerThread.getLooper());
    Message message = myHandler.obtainMessage();
    // 把message发送到myHandler.obtainMessage()目标处,即谁调用的就发送给谁
    Bundle bundle = new Bundle();
    // 通过bundle添加数据
    bundle.putInt("age", 10);
    bundle.putString("name", "john");
    // 将bundle信息添加进去
    message.setData(bundle);
    message.sendToTarget();
  }

  class MyHandler extends Handler {

    public MyHandler(Looper looper) {
      super(looper);
      // TODO Auto-generated constructor stub
    }

    @Override
    public void handleMessage(Message msg) {
      Bundle bundle = msg.getData();
      int age = bundle.getInt("age");
      String name = bundle.getString("name");
      System.out.println("年龄" + age + "名字" + name);
          }

  }

你可能感兴趣的:(android开发教程之使用looper处理消息队列)