The android development tutorial USES looper to process message queues

  • 2020-05-24 06:10:41
  • OfStack


package com.yanjun; 
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 HandlerActivity extends Activity { 
  @Override 
  public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
      //  through HandlerThread Object to implement the use looper The ability to process message queues  
    HandlerThread handlerThread = new HandlerThread("handlerThread"); 
    //  Must be called to make the thread run start() 
    handlerThread.start(); 
    MyHandler myHandler = new MyHandler(handlerThread.getLooper()); 
    Message message = myHandler.obtainMessage(); 
    //  the message Sent to the myHandler.obtainMessage() At the target, it is sent to whoever calls it  
    Bundle bundle = new Bundle(); 
    //  through bundle Add data  
    bundle.putInt("age", 10); 
    bundle.putString("name", "john"); 
    //  will bundle Information is added  
    message.setData(bundle); 
    message.sendToTarget(); 
  } 
  class MyHandler extends Handler { 
    public MyHandler(Looper looper) { 
      super(looper); 
      // TODO Auto-generated constructor stub 
    } 
    @Override 
    public void handleMessage(Message msg) { 
      Bundle bundle = msg.getData(); 
      int age = bundle.getInt("age"); 
      String name = bundle.getString("name"); 
      System.out.println(" age " + age + " The name " + name); 
          } 
  } 


Related articles: