Android進(jìn)程間通訊(1)–Bundle和文件共享
前言:之前記錄過(guò)android的IPC方式有Bundle,文件共享,Messenger,AIDL,ContentProvider和socket。后面將詳解這幾種IPC方式。按類別原理分類,實(shí)際上方式可以分為4種:1.Bundle 2.文件共享 3.Binder,包括Messenger,AIDL, ContentProvider 4.socket。接下來(lái)講解Bundle和文件共享的使用
android四大組件中的三大組件(Activity, Service, Receiver)都支持在Intent傳遞Bundle數(shù)據(jù),由于Bundle實(shí)現(xiàn)了Parcelable接口,所以可以十分方便的在進(jìn)程間傳輸,當(dāng)然我們傳輸?shù)臄?shù)據(jù)必須能夠被序列化,比如基本類型、實(shí)現(xiàn)了Parcelable接口的對(duì)象、實(shí)現(xiàn)了Serializable接口的對(duì)象以及一些Android所支持的特殊對(duì)象。
在同一個(gè)android應(yīng)用中創(chuàng)建多進(jìn)程,需要修改AndroidManifest.xml中process屬性,即在四大組件的根節(jié)點(diǎn)添加android:process=”hdc.video”,即可創(chuàng)建一個(gè)新的名為hdc.video的進(jìn)程
? ? ? ? ? android:configChanges="keyboardHidden|orientation|screenSize"
? ? ? ? ? android:exported="true"
? ? ? ? ? android:screenOrientation="portrait"
? ? ? ? ? android:process="hdc.video">
而應(yīng)用的默認(rèn)進(jìn)程是應(yīng)用的包名,也可以在application根節(jié)點(diǎn)修改process屬性進(jìn)行更改
? ? ? ? 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” 進(jìn)程的MainActivity需要傳遞數(shù)據(jù)到android:process=”hdc.video”的進(jìn)程的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ā)讀寫文件可以沒(méi)有限制地進(jìn)行,甚至兩個(gè)線程對(duì)同一個(gè)文件進(jìn)行寫操作都是允許的。通過(guò)文件交換數(shù)據(jù)使得進(jìn)程間的通訊很好進(jìn)行,但是其弊端就是可能存在數(shù)據(jù)異常,延遲等問(wèn)題。通過(guò)文件共享的方式共享數(shù)據(jù)對(duì)文件的格式是沒(méi)有要求的,可以是文本文件也可以是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();
其他進(jìn)程或當(dāng)前進(jìn)程其他地方使用時(shí)只需要獲取起數(shù)據(jù)即可:
? ? ? ? context.getSharedPreferences("user_preferences",Activity.MODE_PRIVATE)
? ? ? ? String user_id = preference.getString("user_id","");
上面兩種方式是比較常用的進(jìn)程間通訊方式,也是比較簡(jiǎn)單的IPC方式。