---------------------
作者:SJRDDS
來源:CSDN
原文:https://blog.csdn.net/yiranruyuan/article/details/78049219
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!
作者:SJRDDS
來源:CSDN
原文:https://blog.csdn.net/yiranruyuan/article/details/78049219
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!
Bundle主要用於傳遞數據;它保存的數據,是以key-value(鍵值對)的形式存在的。
Bundle經常使用在Activity之間或者線程間傳遞數據,傳遞的數據可以是boolean、byte、int、long、float、double、string等基本類型或它們對應的數組,也可以是對象或對象數組。
當Bundle傳遞的是對象或對象數組時,必須實現Serializable 或Parcelable接口。
Bundle提供了各種常用類型的putXxx()/getXxx()方法,用於讀寫基本類型的數據。(各種方法可以查看API)
在activity間傳遞信息
Bundle bundle = new Bundle(); //得到bundle對象 bundle.putString("sff", "value值"); //key-"sff",通過key得到value-"value值"(String型) bundle.putInt("iff", 175); //key-"iff",value-175 intent.putExtras(bundle); //通過intent將bundle傳到另個Activity startActivity(intent);
讀取數據
Bundle bundle = this.getIntent().getExtras(); //讀取intent的數據給bundle對象 String str1 = bundle.getString("sff"); //通過key得到value int int1 = bundle.getInt("iff");
線程間傳遞
通過Handler將帶有dundle數據的message放入消息隊列,其他線程就可以從隊列中得到數據
1 Message message=new Message();//new一個Message對象 2 3 message.what = MESSAGE_WHAT_2;//給消息做標記 4 5 Bundle bundle = new Bundle(); //得到Bundle對象 6 7 bundle.putString("text1","消息傳遞參數的例子!"); //往Bundle中存放數據 8 9 bundle.putInt("text2",44); //往Bundle中put數據 10 11 message.setData(bundle);//mes利用Bundle傳遞數據 12 13 mHandler.sendMessage(message);//Handler將消息放入消息隊列
讀取數據
這里用的是Handler的handleMessage(Message msg)方法處理數據
1 String str1=msg.getData().getString("text1"); 2 3 int int1=msg.getData().getString("text2");