1>Hanlder与线程:
(1)通一个线程中执行;
(2)
2>Bunlde的用法:
(1)类似Map
(2)Bundle b=new Bundle();
b.put("age",20);
b.put("name",jobs);
(3)Message与Bundle的使用;
3>在新线程中处理消息的方法:
4>Loop的使用:(HanlderTread)
/生成一个HandlerThread对象,实现了使用Looper来处理消息队列的功能,这个类由Android应用程序
eg:
import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.SystemClock;
public class HandlerTest extends Activity { private Handler handler = new Handler(); public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // sendMessage(); //handler.post(r); setContentView(R.layout.main); Thread t = new Thread(r); t.start(); System.out.println("activity--->" + Thread.currentThread().getId()); System.out.println("activityname--->" + Thread.currentThread().getName()); } Runnable r = new Runnable(){
@Override public void run() { // TODO Auto-generated method stub System.out.println("handler--->" + Thread.currentThread().getId()); System.out.println("handlername--->" + Thread.currentThread().getName()); try { Thread.sleep(10000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } };
} |
import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.HandlerThread; import android.os.Looper; import android.os.Message;
public class HandlerTest2 extends Activity {
@Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub 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(); } 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"); System.out.println("age is " + age + ", name is" + name); System.out.println("Handler--->" + Thread.currentThread().getId()); System.out.println("handlerMessage"); } } }
|
阅读(675) | 评论(0) | 转发(0) |