- 博客分类:
- Android 开发学习
- package com.easyway.android.basic;
- import android.app.Activity;
- import android.os.Bundle;
- import android.os.Handler;
- import android.os.HandlerThread;
- import android.os.Looper;
- import android.os.Message;
- import android.widget.EditText;
- /**
- *
- * Android中HandlerThread的使用的方式
- *
- * @author longgangbai
- *
- */
- public class AndroidHandlerThread extends Activity{
- /**
- *
- */
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- //打印了当前线程的ID
- System.out.println("Activity-->" + Thread.currentThread().getId());
- //生成一个HandlerThread对象,实现了使用Looper来处理消息队列的功能,这个类由Android应用程序框架提供
- HandlerThread handlerThread = new HandlerThread("handler_thread");
- //在使用HandlerThread的getLooper()方法之前,必须先调用该类的start();
- handlerThread.start();
- //获取处理器
- MyHandler myHandler = new MyHandler(handlerThread.getLooper());
- //获取信息
- Message msg = myHandler.obtainMessage();
- //将msg发送到目标对象,所谓的目标对象,就是生成该msg对象的handler对象
- Bundle b = new Bundle();
- b.putInt("age", 20);
- b.putString("name", "Jhon");
- //设置数据
- msg.setData(b);
- //发送消息到队列
- msg.sendToTarget();
- }
- /**
- * 继承Handler类
- *
- * @author longgangbai
- *
- */
- class MyHandler extends Handler{
- public MyHandler(){
- }
- public MyHandler(Looper looper){
- super(looper);
- }
- /**
- * 更改界面的方法
- */
- @Override
- public void handleMessage(Message msg) {
- Bundle b = msg.getData();
- int age = b.getInt("age");
- String name = b.getString("name");
- EditText text=(EditText)findViewById(R.id.txtCityName);
- text.setText("Name ="+name);
- System.out.println("age is " + age + ", name is" + name);
- }
- }
- }