Android activity之間資料傳遞和共用的方式之Application

來源:互聯網
上載者:User

標籤:android   style   class   blog   code   java   

1.基於訊息的通訊機制  Intent ---bundle ,extra

    資料類型有限,比如遇到不可序列化的資料Bitmap,InputStream,或者LinkedList鏈表等等資料類型就不太好用。

2.利用static待用資料, public static成員變數;

3.基於外部儲存的傳輸,File/Preference/Sqlite

如果要針對第三方應用需要Content Provider

4.基於IPC的通訊機制

    context 與Service之間的傳輸,如Activity與Service之間的通訊,定義AIDL介面檔案。

5.基於Application Context

 遇到不可序列化的資料Bitmap,InputStream,或者LinkedList鏈表等等資料類型就可以用此種方法。

 

    目前有個項目正好需要用到activity的資料傳遞,在一個activity初始化一個ArrayList<HashMap<String, Map>>對象,然後經過一個tabactivity再傳遞到另外一個activity,一開始直接考慮用putExtra,測試探索資料只能傳遞一次,不符合我的需求,就考慮到了用Application傳遞

Java實現:

 1 public class ContactApp extends Application { 2      3     private ArrayList<HashMap<String, Object>> contactMap =  4             new ArrayList<HashMap<String, Object>>(); 5      6     public void setContactItem(ArrayList<HashMap<String, Object>> item) { 7         this.contactMap = item; 8     } 9     10     public ArrayList<HashMap<String, Object>> getContactItem() {11         return contactMap;12     }13 }

在AndroidManifest.xml中進行配置:

1 <application2     android:name=".model.ContactApp"3     android:icon="@drawable/icon"4     android:label="@string/app_name" >5     ...6 </application>

在其他Activity中進行訪問:

設定資料:

1 ContactApp app = (ContactApp)getApplication();2 app.setContactItem(contactItem);

擷取資料:

1 ContactApp app = (ContactApp)getApplication();2 app.getContactItem();

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.