Android之Handler技术总结

本文深入解析Android中的Handler类,解释其如何用于消息调度和耗时操作,并通过实例展示如何创建和使用Handler来实现消息的发送与接收。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这个是android API 对Handler的描述:

A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. Each Handler instance is associated with a single thread and that thread's message queue. When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it -- from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.

There are two main uses for a Handler: (1) to schedule messages and runnables to be executed as some point in the future; and (2) to enqueue an action to be performed on a different thread than your own.

意思就是说:Handler类允许你发送以及处理一个消息,每个Handler对象都和唯一的一个线程相关联。每当你创建一个Handler对象的时候,这个对象将会和你创建它所在的线程以及该线程的消息队列相互关联。

Handler主要用在消息调度以及一些耗时操作上。

一般的用法是:

一个小例子:

package com.seclab.testhandler;


import android.R.color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.widget.Button;


public class MainActivity extends Activity {
Button btn;
MyHandler myHandler;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button)findViewById(R.id.button1);
myHandler = new MyHandler();
MyThread myThread = new MyThread();
new Thread(myThread).start();
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}






class MyHandler extends Handler {
@Override
public void handleMessage(Message msg) { //处理消息
// TODO Auto-generated method stub
super.handleMessage(msg);
Log.e("xiaotao", "handler message");
Bundle bundle = msg.getData();
String colorString = bundle.getString("color");
MainActivity.this.btn.append(colorString);

}


public MyHandler() {
}


public MyHandler(Looper lp) {
super(lp);
}


}


class MyThread implements Runnable {


@Override
public void run() {

try {
Thread.sleep(10000);
} catch (Exception e) {
e.printStackTrace();
}

Log.e("xiaotao", "thread is running");
Message msgMessage = new Message();
Bundle bundle = new Bundle();
bundle.putString("color", "红色的aaaaaaaaaa");
msgMessage.setData(bundle);
MainActivity.this.myHandler.sendMessage(msgMessage);发送消息
}
}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值