Android的Handler幾種常見的傳值方式


public class handlerThread2 extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        //System.out.println("activity線程ID:"+Thread.currentThread().getId());
        HandlerThread handlerThread = new HandlerThread("handlerThread");
        handlerThread.start();
        MyHandler handler = new MyHandler(handlerThread.getLooper());
        Message msg = handler.obtainMessage();
        
        //msg.arg1 = 123;//傳遞整型數據
        //msg.obj = "asd";傳遞object類型
        
        //利用bundle對象來傳值
        Bundle b = new Bundle();
        b.putInt("ID", 12);
        b.putString("name", "thinkpad");
        msg.setData(b);
        
        msg.sendToTarget();
    }
    class MyHandler extends Handler {

        public MyHandler() {
            super();
        }

        public MyHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            //int args = msg.arg1;
            //String s = (String)msg.obj;
            
            //獲取bundle對象的值
            Bundle b = msg.getData();
            int id = b.getInt("ID");
            String name = b.getString("name");
            System.out.println("id is "+id+", name is "+name);
            
            //System.out.println("handler線程ID:"+Thread.currentThread().getId());
        }
        
    }

}
  運行結果

  那么,bundle具體是個什么東西呢,我們來看一下官方的解釋

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM