一般情況下,一個apk啟動后只會運行在一個進程中,其進程名為AndroidManifest.xml
文件中指定的應用包名,所有的基本組件都會在這個進程中運行。但是如果需要將某些組件(如Service、Activity等)運行在單獨的進程中,就需要用到Android:process屬性了。我們可以為Android的基礎組件指定process屬性來指定它們運行在指定進程中。
實現方法
都是在AndroidManifest.xml
中設置process
實現,也有兩種形式
- 第一種形式如 android:process=":remote",以冒號開頭,冒號后面的字符串原則上是可以隨意指定的。如果我們的包名為“com.example.processtest”,則實際的進程名為“com.example.processtest:remote”。這種設置形式表示該進程為當前應用的私有進程,其他應用的組件不可以和它跑在同一個進程中。
- 第二種情況如android:process="com.example.processtest.remote",以小寫字母開頭,表示運行在一個以這個名字命名的全局進程中,其他應用通過設置相同的ShareUID可以和它跑在同一個進程。
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.processtest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<application
android:name="com.example.processtest.MyApplication"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name">
<activity
android:name=".ProcessTestActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".ProcessTestService"
android:process=":remote">
</service>
</application>
</manifest>
潛在問題
開啟多進程很簡單,但是這樣卻存在很多問題
- 多進程間內存不可見
- Application被多次執行
- 靜態成員的失效
- 文件共享問題
- 斷電調試問題
總結
其實,Android實現應用內多進程并不是簡單的設置屬性process就可以了,而是會產生很多特殊的問題。像前面提到的,Android啟動多進程模式后,不僅靜態變量會失效,而且類似的如同步鎖機制、單例模式也會存在同樣的問題。這就需要我們在使用的時候多加注意。而且設置多進程之后,各個進程間就無法直接相互訪問數據,只能通過AIDL等進程間通信方式來交換數據。