文章目錄
shareUid
- 通過聲明 Shared User id ,擁有同一個 User id 的多個 App 可以配置成運行在同一個進程中,所以可以互相訪問任意數據。
只有在主module中聲明 shareUid 纔會放到最終打包的 AndroidManifest 中。其他功能 module 中聲明 shareUid 不起作用。
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.d.k"
android:sharedUserId="com.d.share">
下面是通過設置相同的 android:sharedUserId B應用獲取A應用保存在 sharedPreferences 的數據。
- A應用代碼
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.d.k"
android:sharedUserId="com.d.share">
// 存儲數據
val sharedPreferences = getSharedPreferences("test", Context.MODE_PRIVATE)
val edit = sharedPreferences.edit()
edit.putString("app", "我是A存儲的數據")
edit.commit()
- B應用代碼
try {
// 獲取 A 應用的 Context 對象 有了 Context後就可以獲取A應用下的資源了。
Context context = this.createPackageContext("com.d.k", Context.CONTEXT_IGNORE_SECURITY);
SharedPreferences sharedPreferences = context.getSharedPreferences("test", Context.MODE_PRIVATE);
String result = sharedPreferences.getString("app", null);
Log.e("secondApp", result);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}