标签:
这个例子是最简单的介绍handler使用的,是将handler绑定到它所建立的线程中.
<span style="font-size:14px;">package com.example.handler1; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; public class MainActivity extends Activity { private TextView text_view = null; private Button start = null; private Button end = null; //使用handler时首先要创建一个handler Handler handler = new Handler(); //要用handler来处理多线程可以使用runnable接口,这里先定义该接口 //线程中运行该接口的run函数 Runnable update_thread = new Runnable() { public void run() { //线程每次执行时输出"UpdateThread..."文字,且自动换行 //textview的append功能和Qt中的append类似,不会覆盖前面 //的内容,只是Qt中的append默认是自动换行模式 text_view.append("\nUpdateThread..."); //延时1s后又将线程加入到线程队列中 handler.postDelayed(update_thread, 1000); } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); text_view = (TextView)findViewById(R.id.text_view); start = (Button)findViewById(R.id.start); start.setOnClickListener(new StartClickListener()); end = (Button)findViewById(R.id.end); end.setOnClickListener(new EndClickListener()); } private class StartClickListener implements OnClickListener { public void onClick(View v) { // TODO Auto-generated method stub //将线程接口立刻送到线程队列中 handler.post(update_thread); } } private class EndClickListener implements OnClickListener { public void onClick(View v) { // TODO Auto-generated method stub //将接口从线程队列中移除 handler.removeCallbacks(update_thread); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } }</span>
<span style="font-size:14px;">package com.example.handler2; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ProgressBar; public class MainActivity extends Activity { private ProgressBar progress_bar = null; private Button start = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); progress_bar = (ProgressBar)findViewById(R.id.progress_bar); start = (Button)findViewById(R.id.start); start.setOnClickListener(new StartOnClickListenr()); } private class StartOnClickListenr implements OnClickListener { public void onClick(View v) { // TODO Auto-generated method stub //让进度条显示出来 progress_bar.setVisibility(View.VISIBLE); //将线程加入到handler的线程队列中 update_progress_bar.post(update_thread); } } //创建一个handler,内部完成处理消息方法 Handler update_progress_bar = new Handler() { @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub //super.handleMessage(msg); //显示进度条 progress_bar.setProgress(msg.arg1); //重新把进程加入到进程队列中 update_progress_bar.post(update_thread); } };//不加这个分号则不能自动添加代码 Runnable update_thread = new Runnable() { int i = 0; public void run() { // TODO Auto-generated method stub i += 10; //首先获得一个消息结构 Message msg = update_progress_bar.obtainMessage(); //给消息结构的arg1参数赋值 msg.arg1 = i; //延时1s,java中的try+catch用来排错处理 try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO: handle exception e.printStackTrace(); } //把消息发送到消息队列中 update_progress_bar.sendMessage(msg); if(i == 100) //把线程从线程队列中移除 update_progress_bar.removeCallbacks(update_thread); } }; @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } }</span>
<span style="font-size:14px;">package com.example.handler3; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.view.Menu; public class MainActivity extends Activity { //新建一个handler private Handler handler = new Handler(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //将runnable加载到handler的线程队列中去 // handler.post(r); Thread t = new Thread(r); t.start(); setContentView(R.layout.activity_main); //打印activtiy线程信息 System.out.println("activity_id---->"+Thread.currentThread().getId()); System.out.println("activity_name---->"+Thread.currentThread().getName()); } Runnable r = new Runnable() { public void run() { // TODO Auto-generated method stub //打印新建线程信息 System.out.println("handler_id---->"+Thread.currentThread().getId()); System.out.println("handler_name---->"+Thread.currentThread().getName()); //延时10s,为了观察主界面中内容出现的时间 try { Thread.sleep(10000); } catch (InterruptedException e) { // TODO: handle exception e.printStackTrace(); } } }; @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } }</span>
package com.example.handler4; 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.view.Menu; public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); System.out.println("activity_ID---->"+Thread.currentThread().getId()); //新建一个HanderThread对象,该对象实现了用Looper来处理消息队列的功能 HandlerThread handler_thread = new HandlerThread("handler_thread"); handler_thread.start(); //MyHandler类是自己继承的一个类,这里采用hand_thread的Looper来初始化它 MyHandler my_handler = new MyHandler(handler_thread.getLooper()); //获得一个消息msg Message msg = my_handler.obtainMessage(); //采用Bundle保存数据,Bundle中存放的是键值对的map,只是它的键值类型和数据类型比较固定而已 Bundle b = new Bundle(); b.putString("whether", "晴天"); b.putInt("temperature", 34); msg.setData(b); //将msg发送到自己的handler中,这里指的是my_handler,调用该handler的HandleMessage方法来处理该mug msg.sendToTarget(); } class MyHandler extends Handler { //空的构造函数 public MyHandler() {} //以Looper类型参数传递的函数,Looper为消息泵,不断循环的从消息队列中得到消息并处理,因此 //每个消息队列都有一个Looper,因为Looper是已经封装好了的消息队列和消息循环的类 public MyHandler(Looper looper) { //调用父类的构造函数 super(looper); } @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub System.out.println("Handler_ID---->"+Thread.currentThread().getId()); System.out.println("Handler_Name---->"+Thread.currentThread().getId()); //将消息中的bundle数据取出来 Bundle b = msg.getData(); String whether = b.getString("whether"); int temperature = b.getInt("temperature"); System.out.println("whether= "+whether+" ,temperature= "+temperature); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } }
总结:
Android中的handler可以用来完成异步的消息出来,即发送消息和接收消息相互独立,可以同时运行。在例1和例2中,实际上handler中使用的线程是与它所在的activity处于同一个主线程,因为handler中调用的runnable接口是直接运行该接口的run函数的,而不是start函数。例3专门比较了这2中情况。例4学会使用怎样在新线程中处理消息的方法。
标签:
原文地址:http://blog.csdn.net/lyp_chd/article/details/51493355