Android進程間通訊(1)–Bundle和文件共享
前言:之前記錄過android的IPC方式有Bundle,文件共享含潘,Messenger枫匾,AIDL,ContentProvider和socket。后面將詳解這幾種IPC方式想帅。按類別原理分類矢门,實際上方式可以分為4種:1.Bundle 2.文件共享 3.Binder撒桨,包括Messenger煤禽,AIDL, ContentProvider 4.socket液样。接下來講解Bundle和文件共享的使用
android四大組件中的三大組件(Activity振亮, Service巧还, Receiver)都支持在Intent傳遞Bundle數(shù)據(jù),由于Bundle實現(xiàn)了Parcelable接口坊秸,所以可以十分方便的在進程間傳輸狞悲,當然我們傳輸?shù)臄?shù)據(jù)必須能夠被序列化,比如基本類型妇斤、實現(xiàn)了Parcelable接口的對象、實現(xiàn)了Serializable接口的對象以及一些Android所支持的特殊對象丹拯。
在同一個android應(yīng)用中創(chuàng)建多進程站超,需要修改AndroidManifest.xml中process屬性,即在四大組件的根節(jié)點添加android:process=”hdc.video”乖酬,即可創(chuàng)建一個新的名為hdc.video的進程
? ? ? ? ? android:configChanges="keyboardHidden|orientation|screenSize"
? ? ? ? ? android:exported="true"
? ? ? ? ? android:screenOrientation="portrait"
? ? ? ? ? android:process="hdc.video">
而應(yīng)用的默認進程是應(yīng)用的包名死相,也可以在application根節(jié)點修改process屬性進行更改
? ? ? ? android:name="com.hdc.voicesAssistant"
? ? ? ? android:allowBackup="true"
? ? ? ? android:icon="@mipmap/dan_icon"
? ? ? ? android:label="@string/app_name"
? ? ? ? android:roundIcon="@mipmap/dan_icon"
? ? ? ? android:supportsRtl="true"
? ? ? ? android:process="com.hdc.voiceAssistant"
? ? ? ? android:theme="@style/AppTheme">
假如android:process=”com.hdc.voiceAssistant” 進程的MainActivity需要傳遞數(shù)據(jù)到android:process=”hdc.video”的進程的WebVideoActivity,則在MainActivity中
? ? ? ? ? Intent intent = new Intent();
? ? ? ? ? ? intent.setClass(MainActivity.this, WebVideoActivity.class);
? ? ? ? ? ? Bundle bundle = new Bundle();
? ? ? ? ? ? bundle.putString("second", "second");
? ? ? ? ? ? intent.putExtras(bundle);
? ? ? ? ? ? startActivity(intent);
在WebVideoActivity的onCreate方法中接受數(shù)據(jù)
? ? ? ? ? Bundle bundle = getIntent().getExtras();
? ? ? ? ? bundle.getString("second");
Android是基于Linux內(nèi)核咬像,使得其并發(fā)讀寫文件可以沒有限制地進行算撮,甚至兩個線程對同一個文件進行寫操作都是允許的。通過文件交換數(shù)據(jù)使得進程間的通訊很好進行县昂,但是其弊端就是可能存在數(shù)據(jù)異常肮柜,延遲等問題。通過文件共享的方式共享數(shù)據(jù)對文件的格式是沒有要求的倒彰,可以是文本文件也可以是XML文件审洞,只要讀寫雙方約定好數(shù)據(jù)格式即可。
Android中常用的方式是SharedPreference,起底層使用的是xml待讳。存數(shù)據(jù)如下:
? ? ? ? context.getSharedPreferences("user_preferences",Activity.MODE_PRIVATE)
? ? ? ? SharedPreferences.Editor editor = mUserPreferences.edit();
? ? ? ? editor.putString("user_id", user_id);
? ? ? ? editor.apply();
其他進程或當前進程其他地方使用時只需要獲取起數(shù)據(jù)即可:
? ? ? ? context.getSharedPreferences("user_preferences",Activity.MODE_PRIVATE)
? ? ? ? String user_id = preference.getString("user_id","");
上面兩種方式是比較常用的進程間通訊方式芒澜,也是比較簡單的IPC方式。