标签:ar os 使用 java on art cti ad as
Handle
用于异步消息处理,发送消息后消息进入队列,然后发送消息函数即可返回,其他函数再逐个取出消息进行处理,也即接收消息与发送消息不是同步进行。
基本使用方法(异步消息处理机制)
(1)创建一个Handle对象
(2)将要执行的操作写在线程对象(runnable)的run方法当中(用匿名内部类实现);在run方法内部,执行postDelayed或者post方法
(3)调用Handle的post方法,将要执行的线程对象添加到队列当中
(线程:实现Runnable接口的run方法)
例程:
public class HandlerActivity extends Activity {
private Button startButton = null;
private Button endButton = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startButton = (Button)findViewById(R.id.startButton);
startButton.setOnClickListener(new StartButtonListener());
endButton = (Button)findViewById(R.id.endButton);
endButton.setOnClickListener(new EndButtonListener());
}
class StartButtonListener implements OnClickListener{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//调用Handle的post方法,将要执行的线程对象添加到队列当中
handler.post(updataThread);
}
}
class EndButtonListener implements OnClickListener{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
handler.removeCallbacks(updataThread);
}
}
//创建一个Handle对象
Handler handler = new Handler();
//将要执行的操作写在线程对象(runnable)的run方法当中(用匿名内部类实现)
Runnable updataThread = new Runnable(){
public void run() {
System.out.println("UpdataThread");
//在run方法内部,执行postDelayed或者post方法
handler.postDelayed(updataThread, 3000);
}
};
}标签:ar os 使用 java on art cti ad as
原文地址:http://blog.csdn.net/zhanhong39/article/details/41747199