Bundle傳遞資料,Handler更新UI
阿新 • • 發佈:2018-11-10
Bundle主要用於傳遞資料;它儲存的資料,是以key-value(鍵值對)的形式存在的。
Bundle經常使用在Activity之間或者執行緒間傳遞資料,傳遞的資料可以是boolean、byte、int、long、float、double、string等基本型別或它們對應的陣列,也可以是物件或物件陣列。
當Bundle傳遞的是物件或物件陣列時,必須實現Serializable 或Parcelable介面。
Bundle提供了各種常用型別的putXxx()/getXxx()方法,用於讀寫基本型別的資料。(各種方法可以檢視API)
在activity間傳遞資訊
Intent intent = newIntent(mContext,DetailActivity.class); Bundle bundle = new Bundle(); bundle.putCharSequence("newsId",newsId); bundle.putString("sff", "value值"); //key-"sff",通過key得到value-"value值"(String型) bundle.putInt("iff", 175); //key-"iff",value-175 intent.putExtras(bundle); //通過intent將bundle傳到另個ActivitystartActivity(intent);
接收資料
//接收Intent發過來的資料 Intent intent = getIntent(); Bundle bundle = intent.getExtras(); String newsId = bundle.getString("newsId");
執行緒間傳遞
通過Handler將帶有dundle資料的message放入訊息佇列,其他執行緒就可以從佇列中得到資料
Message message=new Message();//new一個Message物件 message.what = MESSAGE_WHAT_2;//給訊息做標記 Bundle bundle = new Bundle(); //得到Bundle物件 bundle.putString("text1","訊息傳遞引數的例子!"); //往Bundle中存放資料 bundle.putInt("text2",44); //往Bundle中put資料 message.setData(bundle);//mes利用Bundle傳遞資料 mHandler.sendMessage(message);//Handler將訊息放入訊息佇列
讀取資料
這裡用的是Handler的handleMessage(Message msg)方法處理資料
String str1=msg.getData().getString("text1"); int int1=msg.getData().getString("text2");
轉自:https://blog.csdn.net/yiranruyuan/article/details/78049219