本文共 3558 字,大约阅读时间需要 11 分钟。
如我们上节所讲,在Android中,为应用包的安装,删除各种操作服务的,是PackageManagerSerivce,简称PMS.
如果想要调用PMS的服务,则可以通过Context去调用getPackageManager方法。
这个定义于Context.java中:
/** Return PackageManager instance to find global package information. */ public abstract PackageManager getPackageManager();
我们先来看一张图,了解PackageManager与PMS的关系:
我们下面先以PackageManager中所提供的getApplicationInfo方法为例,看看它是如何被实现的。
ApplicationInfo getApplicationInfo (String packageName,int flags)
支持的标志如下:
public abstract PackageInfo getPackageInfo(String packageName, int flags)throws NameNotFoundException;
ApplicationPackageManager继承了抽象类PackageManager.
final class ApplicationPackageManager extends PackageManager
ApplicationPackageManager是在ContextImpl中被new出来的:
@Override public PackageManager getPackageManager() { if (mPackageManager != null) { return mPackageManager; } IPackageManager pm = ActivityThread.getPackageManager(); if (pm != null) { // Doesn't matter if we make more than one instance. return (mPackageManager = new ApplicationPackageManager(this, pm)); } return null; }
ApplicationPackageManager中的第二个参数pm是沟通PMS的桥梁。
我们来看ActivityThread中getPackageManager的实现:
public static IPackageManager getPackageManager() { if (sPackageManager != null) { return sPackageManager; } IBinder b = ServiceManager.getService("package"); sPackageManager = IPackageManager.Stub.asInterface(b); return sPackageManager; }
在ApplicationPackageManager类中,其实还是对PMS的对应功能的封装。
public ApplicationInfo getApplicationInfo(String packageName, int flags) throws NameNotFoundException { try { ApplicationInfo ai = mPM.getApplicationInfo(packageName, flags, mContext.getUserId());... } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } throw new NameNotFoundException(packageName); }
真正的实现还是要看PMS:
@Override public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { if (!sUserManager.exists(userId)) return null; enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); // writer synchronized (mPackages) { PackageParser.Package p = mPackages.get(packageName); if (DEBUG_PACKAGE_INFO) Log.v( TAG, "getApplicationInfo " + packageName + ": " + p); if (p != null) { PackageSetting ps = mSettings.mPackages.get(packageName); if (ps == null) return null; // Note: isEnabledLP() does not apply here - always return info return PackageParser.generateApplicationInfo( p, flags, ps.readUserState(userId), userId); } if ("android".equals(packageName)||"system".equals(packageName)) { return mAndroidApplication; } if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); } } return null; }
转载地址:http://xfupa.baihongyu.com/