java new handler_Java Handler与Android Handler

java中的handler类直接继承自Object类,jdk 1.6 api是这样描述handler的:

public abstract

class Handler extends

java.lang.Object

java.util.logging.Handler

Handler 对象从 Logger 中获取日志信息,并将这些信息导出。例如,它可将这些信息写入控制台或文件中,也可以将这些信息发送到网络日志服务中,或将其转发到操作系统日志中。

可通过执行 setLevel(Level.OFF) 来禁用 Handler,并可通过执行适当级别的 setLevel 来重新启用。

Handler 类通常使用 LogManager 属性来设置 Handler 的 Filter、Formatter 和 Level 的默认值。有关每个具体的 Handler 类,请参阅指定的文档

abstract void close() 关闭 Handler,并释放所有相关的资源。 abstract void flush() 刷新所有的缓冲输出。 String getEncoding() 返回该 Handler 的字符编码。 ErrorManager

getErrorManager() 获取该 Handler 的 ErrorManager。 Filter getFilter() 获得该 Handler 的当前 Filter。 Formatter getFormatter() 返回该 Handler 的 Formatter。 Level getLevel() 获得用于指定该 Handler 所记录信息的日志级别。 boolean isLoggable(LogRecord

record) 检查该 Handler 是否实际记录给定的 LogRecord。 abstract void publish(LogRecord

record) 发布 LogRecord。 protected void reportError(String msg, Exception

ex, int code) 用于向该 Handler 的 ErrorManager 报告错误的受保护便利方法。 void setEncoding(String

encoding) 设置该 Handler 所用的字符编码。 void setErrorManager(ErrorManager

em) 为该 Handler 定义一个 ErrorManager。 void setFilter(Filter

newFilter) 设置 Filter,以控制该 Handler 的输出。 void setFormatter(Formatter

newFormatter) 设置 Formatter。 void setLevel(Level

newLevel) 设置日志级别,指定该 Handler 所记录的信息级别。

java的handler类是一个抽象类,android的handler是一个普通的类

public class Handler extends Object

android.os.Handler

Class Overview

A Handler allows you to send and

process and

Runnable objects associated with a

thread's

我英语不好,意思大概是一个handler允许你发送和处理消息和一个线程对象与一个线程对象的消息队列相联系。

每一个handler实例与一个单线程还有该线程的消息队列相联系。

当你创建一个handler,被绑定在该线程和它的消息队列上。

传送消息,进入消息队列,执行当他们走出消息队列。

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的两个主要用途:1调度消息,将来执行

2把一个action加入队列在不同的线程中执行

Scheduling messages is accomplished with

the methods.

The post versions allow

you to enqueue Runnable objects to be called by the message queue

when they are received;

the sendMessage versions

allow you to enqueue a object

containing a bundle of data that will be processed by the

Handler's method

(requiring that you implement a subclass of

Handler).

这里主要是介绍handler函数作用。

这些函数主要是将线程,消息加入消息队列

执行在handler子类的handleMessage(message)函数

目前我看到网上的一些例子都是handler的子类在处理消息,handler不是一个普通类吗,又不想java的handler一样是一个抽象类,为什么就不能直接使用handler呢

When posting or sending to a Handler, you can either allow the item

to be processed as soon as the message queue is ready to do so, or

specify a delay before it gets processed or absolute time for it to

be processed. The latter two allow you to implement timeouts,

ticks, and other timing-based behavior.

当你post一个线程或者发送一个消息,你可以马上处理只要消息队列准备好了,也可以在某个时间点执行,或者delay执行

When a process is created for your application, its main thread is

dedicated to running a message queue that takes care of managing

the top-level application objects (activities, broadcast receivers,

etc) and any windows they create. You can create your own threads,

and communicate back with the main application thread through a

Handler. This is done by calling the

same post orsendMessage methods

as before, but from your new thread. The given Runnable or Message

will than be scheduled in the Handler's message queue and processed

when appropriate

当你的应用程序创建了处理,主线程还有消息队列用于关系顶级的应用程序对象如activities, broadcast

receivers,还有窗口创建。你可以创建自己的线程,和主线程交互通过handler。

Android中*

Handler的定义:

* 主要接受子线程发送的数据, 并用此数据配合主线程更新UI。当应用程序启动时,

* Android首先会开启一个主线程 (也就是UI线程) , 主线程为管理界面中的UI控件,进行事件分发, 比如说,

* 你要是点击一个 Button ,Android会分发事件到Button上,来响应你的操作。

* 如果此时需要一个耗时的操作,例如: 联网读取数据,或者读取本地较大的一个文件的时候,你不能把这些操作放在主线程中,

* 如果你放在主线程中的话,界面会出现假死现象, 如果5秒钟还没有完成的话,会收到Android系统的一个错误提示

"强制关闭"。

* 这个时候我们需要把这些耗时的操作,放在一个子线程中,因为子线程涉及到UI更新,Android主线程是线程不安全的,

* 也就是说,更新UI只能在主线程中更新,子线程中操作是危险的。这个时候,Handler就出现了,来解决这个复杂的问题 ,

* 由于Handler运行在主线程中(UI线程中),它与子线程可以通过Message对象来传递数据,

*

这个时候,Handler就承担着接受子线程传过来的(子线程用sedMessage()方法传弟)Message对象(里面包含数据),把这些消息放入主线程队列中,配合主线程进行更新UI。

* Handler一些特点:

* Handler可以分发Message对象和Runnable对象到主线程中,

每个Handler实例,都会绑定到创建他的线程中(一般是位于主线程),

* 它有两个作用: (1): 安排消息或Runnable 在某个主线程中某个地方执行,

(2)安排一个动作在不同的线程中执行

* Handler中分发消息的一些方法

* post(Runnable)

* postAtTime(Runnable,long)

* postDelayed(Runnable,long)

* sendEmptyMessage(int)

* sendMessage(Message)

* sendMessageAtTime(Message,long)

* sendMessageDelayed(Message,long)

*

以上post类方法允许你排列一个Runnable对象到主线程队列中,当需要在不同于主UI线程中执行则需要配合HandlerThread进行使用:

* HandlerThread handlerThread = new

HandlerThread("myHandlerThread");

* handlerThread.start();

* handler = new Handler(handlerThread.getLooper());*

sendMessage类方法, 允许你安排一个带数据的Message对象到队列中,等待更新.

public class HandlerActivity extends Activity {

private TextView textView;

private MyHandler myHandler;

private Button button;

private ProgressBar progressBar;

private MyThread m=new MyThread();

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

textView=(TextView)findViewById(R.id.text);

button=(Button)findViewById(R.id.startButton);

progressBar=(ProgressBar)findViewById(R.id.bar);

progressBar.setMax(100);

button.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View arg0) {

myHandler=new MyHandler();

new Thread(m).start();

System.out.println("onCreate--The Thread is:

"+Thread.currentThread().getId());

}

});

}

//在对UI进行更新时,执行时所在的线程为主UI线程

class MyHandler extends

Handler{//继承Handler类时,必须重写handleMessage方法

public MyHandler(){

}

public MyHandler(Looper l){

super(l);

}

@Override

public void handleMessage(Message msg)

{//执行接收到的通知,此时执行的顺序是按照队列进行,即先进先出

System.out.println("Handler--The ThreadId is:

"+Thread.currentThread().getId());

super.handleMessage(msg);

Bundle b=msg.getData();

String textStr0=textView.getText().toString();

String textStr1=b.getString("textStr");

HandlerActivity.this.textView.setText(textStr0+"

"+textStr1);//更改TextView中的值

int

barValue=b.getInt("barValue");HandlerActivity.this.progressBar.setProgress(barValue);//更改进度条当中的值

}

}

//该线程将会在单独的线程中运行

class MyThread implements Runnable{

int i=1;

@Override

public void run() {

while(i<11){

System.out.println("Thread--The ThreadId is:

"+Thread.currentThread().getId());

try {

Thread.sleep(1000);

} catch (InterruptedException e) {

e.printStackTrace();

}

Message msg=new Message();

Bundle b=new Bundle();

b.putString("textStr", "线程运行"+i+"次");

b.putInt("barValue", i*10);

i++;

msg.setData(b);

HandlerActivity.this.myHandler.sendMessage(msg);//通过sendMessage向Handler发送更新UI的消息

}

}

}

}

public class HandlerActivity extends Activity {

private TextView textView;

private MyHandler myHandler;

private Button button;

private ProgressBar progressBar;

private MyThread m=new MyThread();

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

textView=(TextView)findViewById(R.id.text);

button=(Button)findViewById(R.id.startButton);

progressBar=(ProgressBar)findViewById(R.id.bar);

progressBar.setMax(100);

button.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View arg0) {

myHandler=new MyHandler();

new Thread(m).start();

System.out.println("onCreate--The Thread is:

"+Thread.currentThread().getId());

}

});

}

//在对UI进行更新时,执行时所在的线程为主UI线程

class MyHandler extends

Handler{//继承Handler类时,必须重写handleMessage方法

public MyHandler(){

}

public MyHandler(Looper l){

super(l);

}

Handler的定义:

* 主要接受子线程发送的数据, 并用此数据配合主线程更新UI。当应用程序启动时,

* Android首先会开启一个主线程 (也就是UI线程) , 主线程为管理界面中的UI控件,进行事件分发, 比如说,

* 你要是点击一个 Button ,Android会分发事件到Button上,来响应你的操作。

* 如果此时需要一个耗时的操作,例如: 联网读取数据,或者读取本地较大的一个文件的时候,你不能把这些操作放在主线程中,

* 如果你放在主线程中的话,界面会出现假死现象, 如果5秒钟还没有完成的话,会收到Android系统的一个错误提示

"强制关闭"。

* 这个时候我们需要把这些耗时的操作,放在一个子线程中,因为子线程涉及到UI更新,Android主线程是线程不安全的,

* 也就是说,更新UI只能在主线程中更新,子线程中操作是危险的。这个时候,Handler就出现了,来解决这个复杂的问题 ,

* 由于Handler运行在主线程中(UI线程中),它与子线程可以通过Message对象来传递数据,

*

这个时候,Handler就承担着接受子线程传过来的(子线程用sedMessage()方法传弟)Message对象(里面包含数据),把这些消息放入主线程队列中,配合主线程进行更新UI。*

Handler一些特点:

* Handler可以分发Message对象和Runnable对象到主线程中,

每个Handler实例,都会绑定到创建他的线程中(一般是位于主线程),

* 它有两个作用: (1): 安排消息或Runnable 在某个主线程中某个地方执行,

(2)安排一个动作在不同的线程中执行

* Handler中分发消息的一些方法

* post(Runnable)

* postAtTime(Runnable,long)

* postDelayed(Runnable,long)

* sendEmptyMessage(int)

* sendMessage(Message)

* sendMessageAtTime(Message,long)

* sendMessageDelayed(Message,long)

*

以上post类方法允许你排列一个Runnable对象到主线程队列中,当需要在不同于主UI线程中执行则需要配合HandlerThread进行使用:

* HandlerThread handlerThread = new

HandlerThread("myHandlerThread");

* handlerThread.start();

* handler = new Handler(handlerThread.getLooper());

* sendMessage类方法, 允许你安排一个带数据的Message对象到队列中,等待更新.

@Override

public void handleMessage(Message msg)

{//执行接收到的通知,此时执行的顺序是按照队列进行,即先进先出

System.out.println("Handler--The ThreadId is:

"+Thread.currentThread().getId());

super.handleMessage(msg);

Bundle b=msg.getData();

String textStr0=textView.getText().toString();

String textStr1=b.getString("textStr");

HandlerActivity.this.textView.setText(textStr0+"

"+textStr1);//更改TextView中的值

int barValue=b.getInt("barValue");

HandlerActivity.this.progressBar.setProgress(barValue);//更改进度条当中的值

}

}

//该线程将会在单独的线程中运行

class MyThread implements Runnable{

int i=1;

@Override

public void run() {

while(i<11){

System.out.println("Thread--The ThreadId is:

"+Thread.currentThread().getId());

try {

Thread.sleep(1000);

} catch (InterruptedException e) {

e.printStackTrace();

}

Message msg=new Message();

Bundle b=new Bundle();

b.putString("textStr", "线程运行"+i+"次");

b.putInt("barValue", i*10);

i++;

msg.setData(b);

HandlerActivity.this.myHandler.sendMessage(msg);//通过sendMessage向Handler发送更新UI的消息

}

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值