1、概述:
appops是在现有权限机制上新增的一套权限管理机制,主要针对一些高危的非必须系统应用的权限,比如在其他应用上显示悬浮窗。
</br>
2、服务启动:
appops服务在ActivityManagerService服务启动的时候一同启动:
mAppOpsService = mInjector.getAppOpsService(new File(systemDir, "appops.xml"), mHandler);
mAppOpsService.startWatchingMode(AppOpsManager.OP_RUN_IN_BACKGROUND, null,
new IAppOpsCallback.Stub() {
@Override public void opChanged(int op, int uid, String packageName) {
if (op == AppOpsManager.OP_RUN_IN_BACKGROUND && packageName != null) {
if (mAppOpsService.checkOperation(op, uid, packageName)
!= AppOpsManager.MODE_ALLOWED) {
runInBackgroundDisabled(uid);
}
}
}
});
在AppOpsService构造函数中:传入的文件:/data/system/appops.xml,该文件主要记录各应用权限情况,如下:
<pkg n="com.android.server.telecom">
<uid n="1000" p="true">
<op n="6" t="1539203309925" pu="0" pp="com.android.providers.contacts" />
<op n="7" t="1538515682359" pu="0" pp="com.android.providers.contacts" />
<op n="23" r="1538042158836" />
<op n="27" t="1538042162413" pu="0" />
</uid>
</pkg>
public AppOpsService(File storagePath, Handler handler) {
LockGuard.installLock(this, LockGuard.INDEX_APP_OPS);
mFile = new AtomicFile(storagePath);
mHandler = handler;
mLooper = Looper.myLooper();
readState();
}
通过readState将appops文件中记录的内容读取到本地的数组:mUidStates中
protected final SparseArray<UidState> mUidStates = new SparseArray<>();
void readState() {
...
try {
XmlPullParser parser = Xml.newPullParser();
parser.setInput(stream, StandardCharsets.UTF_8.name());
int type;
while ((type = parser.next()) != XmlPullParser.START_TAG
&& type != XmlPullParser.END_DOCUMENT) {
;
}
if (type != XmlPullParser.START_TAG) {
throw new IllegalStateException("no start tag found");
}
int outerDepth = parser.getDepth();
while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
&& (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
continue;
}
String tagName = parser.getName();
if (tagName.equals("pkg")) {
readPackage(parser);
} else if (tagName.equals("uid")) {
readUidOps(parser);
} else {
Slog.w(TAG, "Unknown element under <app-ops>: "
+ parser.getName());
XmlUtils.skipCurrentTag(parser);
}
}
success = true;
...
}
public void systemReady() {
synchronized (this) {
boolean changed = false;
for (int i = mUidStates.size() - 1; i >= 0; i--) {
UidState uidState = mUidStates.valueAt(i);
String[] packageNames = getPackagesForUid(uidState.uid);
if (ArrayUtils.isEmpty(packageNames)) {
uidState.clear();
mUidStates.removeAt(i);
changed = true;
continue;
}
ArrayMap<String, Ops> pkgs = uidState.pkgOps;
if (pkgs == null) {
continue;
}
移除mUidState数组中已经卸载的应用
Iterator<Ops> it = pkgs.values().iterator();
while (it.hasNext()) {
Ops ops = it.next();
int curUid = -1;
try {
curUid = AppGlobals.getPackageManager().