IPC简介(一)
IPC是Inter-Process Communication的缩写,含义为进程间通信或者跨进程通信,指两个进程之间进行数据交换的过程。在Android中最有特色的进程间通信方式就是Binder,通过Binder可以轻松地实现进程间通信,同时Android还支持socket,通过socket可以实现任意两个终端之间的通信,当然可以是一个设备的两个进程。
Android中的多进程模式
通常情况下,Android中的多进程指的是同一个应用中存在多个进程的情况,在Android中使用多进程的唯一方法,就是给四大组件(Activity、Service、Receiver、ContentProvider)在AndroidMenifest中指定android:process属性。另外一种非常规的多进程方法,是通过JNI在native层去fork一个新的进程。
在设置的AndroidMenifest.xml文件中,有如下配置,指定ApnSettingsActivity运行在com.android.phone的进程中android:process="com.android.phone"
<!-- Runs in the phone process since it needs access to UiccController -->
<activity android:name="Settings$ApnSettingsActivity"
android:label="@string/apn_settings"
android:launchMode="singleTask"
android:taskAffinity="com.android.settings"
android:configChanges="orientation|keyboardHidden|screenSize"
android:parentActivityName="Settings$NetworkDashboardActivity"
android:process="com.android.phone">
<intent-filter android:priority="1">
<action android:name="android.settings.APN_SETTINGS" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.VOICE_LAUNCH" />
</intent-filter>
<meta-data android:name="com.android.settings.PRIMARY_PROFILE_CONTROLLED"
android:value="true" />
<meta-data android:name="com.android.settings.FRAGMENT_CLASS"
android:value="com.android.settings.ApnSettings" />
</activity>
另外还有一种写法如下所示android:process=":CryptKeeper"
<activity android:name=".CryptKeeper"
androidprv:systemUserOnly="true"
android:immersive="true"
android:launchMode="singleTop"
android:excludeFromRecents="true"
android:theme="@style/Theme.CryptKeeper"
android:configChanges="mnc|mcc|keyboard|keyboardHidden|uiMode|touchscreen"
android:windowSoftInputMode="adjustResize"
android:screenOrientation="nosensor"
android:process=":CryptKeeper">
<intent-filter android:priority="10">
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.HOME" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
对于这两种写法的区别如下:“:”的含义是指要在当前的进程名前面附加上当前的包名,是一种简写的方法,此进程属于当前应用的私有进程,其他应用的组件不可以和它跑在同一个进程中,而不以“:”开头的进程属于全局进程,其他应用可以通过ShareUID方式和它跑在同一个进程中。Android系统会为每一个应用分配一个唯一的UID,具有相同UID的应用才能共享数据。两个应用通过ShareUID跑在同一个进程中要求这两个应用具有相同的签名和ShareUID,在这种情况下,这两个应用可以互相访问对方的私有数据。
一般来说,使用多线程会造成以下问题:
- 静态成员和单例模式完全失效
- 线程同步机制完全失效
- SharedPreferences的可靠性下降
- Application会多次创建
虽然多进程的使用会带来一些问题,但是也应该要去正视它,为了解决这些问题,系统提供了很多跨进程通信的方法来实现数据交互,例如使用Intent来传递数据,共享文件,SharedPreferences,基于Binder的Messenger和AIDL以及Socket等。
网友评论