PID和UID存在的意义

Pid是进程ID,Uid是用户ID,只是Android和计算机不一样,计算机每个用户都具有一个Uid,哪个用户start的程序,这个程序的Uid就是那个用户,而Android中每个程序都有一个Uid,默认情况下,Android会给每个程序分配一个普通级别互不相同的Uid,如果应用之间要互相调用,只能是Uid相同才行,这就使得共享数据具有了一定安全性,每个软件之间是不能随意获得数据的。而同一个application只有一个Uid,所以application下的Activity之间不存在访问权限的问题。

如何实现两个应用uid共享?

首先需要在两个应用的AndroidManifest.xml中都定义相同的sharedUserId,如:android:sharedUserId="com.test";

定义后可以通过adb shell cat data/system/packages.list(限于eng或userdebug版) 进行确认两个应用的uid是否相同了,

输出结果似如:

com.example.testdatabase 10124 1 /data/data/com.example.testdatabase default none

com.example.test_6_3_database 10124 1 /data/data/com.example.test_6_3_database default none

证明uid已经是一样了。

uid共享res资源实例

假设我们有这样一个需求,A和B是两个应用,现在要求在A中获取B的一张名字为send_bg的图片资源,那么先将A和B的注册文件的AndroidManifest.xml节点添加sharedUserId,并且赋值相同,然后在A中可以用如下方式实现:

Context thdContext = null;

try {

thdContext = createPackageContext(

"com.example.testdatabase",

Context.CONTEXT_IGNORE_SECURITY);

Resources res = thdContext.getResources();

int menuIconId = res.getIdentifier("send_bg", "drawable",

"com.example.testdatabase");

Drawable drawable = res.getDrawable(menuIconId);

mButton.setBackgroundDrawable(drawable);

} catch (NameNotFoundException e) {

e.printStackTrace();

}

uid共享database实例

假设我们有这样一个需求,A和B是两个应用,现在要求在A中要获取B的数据库,那么先将A和B的注册文件的AndroidManifest.xml节点添加sharedUserId,并且赋值相同,然后在A中可以用如下方式实现:

Context thdContext = null;

try {

thdContext = createPackageContext(

"com.example.testdatabase",

Context.CONTEXT_IGNORE_SECURITY);

String dbPath = thdContext.getDatabasePath("BookStore.db")

.getAbsolutePath();

SQLiteDatabase db = SQLiteDatabase.openDatabase(dbPath,

null, SQLiteDatabase.OPEN_READWRITE);

Cursor cursor = db.query("Book", null, null, null, null,

null, null);

if (cursor.moveToFirst()) {

do {

String name = cursor.getString(cursor

.getColumnIndex("name"));

Log.d(TAG, "name: " + name);

} while (cursor.moveToNext());

}

} catch (NameNotFoundException e) {

e.printStackTrace();

}

我们还可以通过uid共享其他资源或者Preference等等。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐