Java Code Examples for android.content.pm.PackageManager#GET_SIGNATURES

The following examples show how to use android.content.pm.PackageManager#GET_SIGNATURES . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Utils.java    From SecuritySample with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the encoded representation of the first signing certificated used to sign current APK
 *
 * @param ctx
 * @return
 */
private static byte[] getSigningKeyCertificate(Context ctx) {
    try {
        PackageManager pm = ctx.getPackageManager();
        String packageName = ctx.getPackageName();
        int flags = PackageManager.GET_SIGNATURES;
        PackageInfo packageInfo = pm.getPackageInfo(packageName, flags);
        Signature[] signatures = packageInfo.signatures;

        if (signatures != null && signatures.length >= 1) {
            //takes just the first signature, TODO: handle multi signed apks
            byte[] cert = signatures[0].toByteArray();
            InputStream input = new ByteArrayInputStream(cert);
            CertificateFactory cf = CertificateFactory.getInstance("X509");
            X509Certificate c = (X509Certificate) cf.generateCertificate(input);
            return c.getEncoded();
        }
    } catch (Exception e) {
        Log.w(TAG, e);
    }
    return null;
}
 
Example 2
Source File: VPackageManagerService.java    From container with GNU General Public License v3.0 6 votes vote down vote up
@Override
public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
	synchronized (mPackages) {
		PackageParser.Package pkg = mPackages.get(packageName);
		if (pkg != null) {
			AppSetting setting = (AppSetting) pkg.mExtras;
			if ((flags & PackageManager.GET_SIGNATURES) != 0 && pkg.mSignatures == null) {
				if (pkg.mAppMetaData != null && pkg.mAppMetaData.containsKey(Constants.FEATURE_FAKE_SIGNATURE)) {
					String sig = pkg.mAppMetaData.getString("fake-signature");
					if (sig != null) {
						pkg.mSignatures = new Signature[] {new Signature(sig)};
					}
				} else {
					PackageParserCompat.collectCertificates(setting.parser, pkg, PackageParser.PARSE_IS_SYSTEM);
				}
			}
			PackageInfo packageInfo = PackageParserCompat.generatePackageInfo(pkg, flags,
					getFirstInstallTime(pkg), getLastInstallTime(pkg));
			if (packageInfo != null) {
				ComponentFixer.fixApplicationInfo(setting, packageInfo.applicationInfo, userId);
				return packageInfo;
			}
		}
	}
	return null;
}
 
Example 3
Source File: IPluginManagerImpl.java    From DroidPlugin with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public PackageInfo getPackageInfo(String packageName, int flags) throws RemoteException {
    waitForReadyInner();
    try {
        String pkg = getAndCheckCallingPkg(packageName);
        if (pkg != null && !TextUtils.equals(packageName, mContext.getPackageName())) {
            enforcePluginFileExists();
            PluginPackageParser parser = mPluginCache.get(pkg);
            if (parser != null) {
                PackageInfo packageInfo = parser.getPackageInfo(flags);
                if (packageInfo != null && (flags & PackageManager.GET_SIGNATURES) != 0 && packageInfo.signatures == null) {
                    packageInfo.signatures = mSignatureCache.get(packageName);
                }
                return packageInfo;
            }
        }
    } catch (Exception e) {
        handleException(e);
    }
    return null;
}
 
Example 4
Source File: PackageUtils.java    From springreplugin with Apache License 2.0 5 votes vote down vote up
/**
 * 获取PackageInfo对象
 * 该方法解决了Android 2.x环境不能获取签名的系统问题,故可以“全面使用”
 */
public static PackageInfo getPackageArchiveInfo(PackageManager pm, String pkgFilePath, int flags) {
    PackageInfo info = null;
    try {
        info = pm.getPackageArchiveInfo(pkgFilePath, flags);
    } catch (Throwable e) {
        if (LogDebug.LOG) {
            e.printStackTrace();
        }
    }

    if (info == null) {
        return null;
    }

    // Android 2.x的系统通过常规手段(pm.getPackageArchiveInfo)时会返回null,只能通过底层实现
    // 判断依据:1、想要签名;2、没拿到签名;3、Android 4.0以前
    if ((flags & PackageManager.GET_SIGNATURES) != 0) {
        if (info.signatures == null) {
            if (Build.VERSION.SDK_INT < 14) {
                info.signatures = getPackageArchiveSignaturesInfoAndroid2x(pkgFilePath);
            }
        }
    }

    return info;
}
 
Example 5
Source File: GeneratePackageInfoHook.java    From haystack with GNU General Public License v3.0 5 votes vote down vote up
@DexReplace
static PackageInfo hook(PackageInfo pi, Context context, PackageParser.Package p, int flags, int userId) {
    try {
        if ((flags & PackageManager.GET_SIGNATURES) != 0) {
            if (p.requestedPermissions != null) {
                if (p.requestedPermissions.contains(FakeSignatureCore.PERMISSION)) {
                    if (getGlobalEnable(pi, context, p, flags, userId) &&
                            getPerAppEnable(pi, context, p, flags, userId)) {
                        if (p.mAppMetaData != null) {
                            Object fakeSignatureData = p.mAppMetaData.get(FakeSignatureCore.METADATA);
                            if (fakeSignatureData != null) {
                                if (fakeSignatureData instanceof String) {
                                    pi.signatures = new Signature[] { new Signature((String) fakeSignatureData) };
                                } else {
                                    Log.e("GeneratePackageInfoHook", "invalid '" + FakeSignatureCore.METADATA + "' metadata");
                                }
                            } else {
                                Log.e("GeneratePackageInfoHook", "missing 'fake-signature' metadata");
                            }
                        } else {
                            Log.e("GeneratePackageInfoHook", "null mAppMetaData");
                        }
                    }
                }
            } else {
                Log.e("GeneratePackageInfoHook", "null requestedPermissions");
            }
        }
    } catch (Throwable t) {
        // We should never die because of any failures, this is system code!
        // Eating up instances of Error might seem excessive, but they can be
        // the result of improperly applied patches so we will handle them here.
        Log.e("GeneratePackageInfoHook", "hook exception", t);
    }
    return pi;
}
 
Example 6
Source File: GeneratePackageInfoHook.java    From haystack with GNU General Public License v3.0 5 votes vote down vote up
@DexReplace
static PackageInfo hook(PackageInfo pi, Context context, PackageParser.Package p, int flags, int userId) {
    try {
        if ((flags & PackageManager.GET_SIGNATURES) != 0) {
            if (p.requestedPermissions != null) {
                if (p.requestedPermissions.contains(FakeSignatureCore.PERMISSION)) {
                    if (getGlobalEnable(pi, context, p, flags, userId) &&
                            getPerAppEnable(pi, context, p, flags, userId)) {
                        if (p.mAppMetaData != null) {
                            Object fakeSignatureData = p.mAppMetaData.get(FakeSignatureCore.METADATA);
                            if (fakeSignatureData != null) {
                                if (fakeSignatureData instanceof String) {
                                    pi.signatures = new Signature[] { new Signature((String) fakeSignatureData) };
                                } else {
                                    Log.e("GeneratePackageInfoHook", "invalid '" + FakeSignatureCore.METADATA + "' metadata");
                                }
                            } else {
                                Log.e("GeneratePackageInfoHook", "missing 'fake-signature' metadata");
                            }
                        } else {
                            Log.e("GeneratePackageInfoHook", "null mAppMetaData");
                        }
                    }
                }
            } else {
                Log.e("GeneratePackageInfoHook", "null requestedPermissions");
            }
        }
    } catch (Throwable t) {
        // We should never die because of any failures, this is system code!
        // Eating up instances of Error might seem excessive, but they can be
        // the result of improperly applied patches so we will handle them here.
        Log.e("GeneratePackageInfoHook", "hook exception", t);
    }
    return pi;
}
 
Example 7
Source File: RefreshInstalledListTask.java    From apkextractor with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void run(){
    PackageManager manager=context.getApplicationContext().getPackageManager();
    SharedPreferences settings= SPUtil.getGlobalSharedPreferences(context);
    int flag=0;
    if(settings.getBoolean(Constants.PREFERENCE_LOAD_PERMISSIONS,Constants.PREFERENCE_LOAD_PERMISSIONS_DEFAULT))flag|=PackageManager.GET_PERMISSIONS;
    if(settings.getBoolean(Constants.PREFERENCE_LOAD_ACTIVITIES,Constants.PREFERENCE_LOAD_ACTIVITIES_DEFAULT))flag|=PackageManager.GET_ACTIVITIES;
    if(settings.getBoolean(Constants.PREFERENCE_LOAD_RECEIVERS,Constants.PREFERENCE_LOAD_RECEIVERS_DEFAULT))flag|=PackageManager.GET_RECEIVERS;
    if(settings.getBoolean(Constants.PREFERENCE_LOAD_APK_SIGNATURE,Constants.PREFERENCE_LOAD_APK_SIGNATURE_DEFAULT))flag|=PackageManager.GET_SIGNATURES;
    if(settings.getBoolean(Constants.PREFERENCE_LOAD_SERVICES,Constants.PREFERENCE_LOAD_SERVICES_DEFAULT))flag|=PackageManager.GET_SERVICES;
    if(settings.getBoolean(Constants.PREFERENCE_LOAD_PROVIDERS,Constants.PREFERENCE_LOAD_PROVIDERS_DEFAULT))flag|=PackageManager.GET_PROVIDERS;
    final List<PackageInfo> list = new ArrayList<>();
    synchronized (RefreshInstalledListTask.class){//加锁是在多线程请求已安装列表时PackageManager可能会抛异常 ParceledListSlice: Failure retrieving array;
        list.clear();
        list.addAll(manager.getInstalledPackages(flag));
    }
    Global.handler.post(new Runnable() {
        @Override
        public void run() {
            if(listener!=null)listener.onRefreshProgressStarted(list.size());
        }
    });
    for(int i=0;i<list.size();i++){
        if(isInterrupted)return;
        PackageInfo info=list.get(i);
        boolean info_is_system_app=((info.applicationInfo.flags& ApplicationInfo.FLAG_SYSTEM)>0);
        final int current=i+1;
        Global.handler.post(new Runnable() {
            @Override
            public void run() {
                if(listener!=null)listener.onRefreshProgressUpdated(current,list.size());
            }
        });
        if(!flag_system&&info_is_system_app)continue;
        list_sum.add(new AppItem(context,info));
    }
    if(isInterrupted)return;
    AppItem.sort_config=settings.getInt(Constants.PREFERENCE_SORT_CONFIG,0);
    Collections.sort(list_sum);
    synchronized (Global.app_list){
        Global.app_list.clear();
        Global.app_list.addAll(list_sum);//向全局list保存一个引用
    }
    GetSignatureInfoTask.clearCache();
    Global.handler.post(new Runnable() {
        @Override
        public void run() {
            if(listener!=null)listener.onRefreshCompleted(list_sum);
        }
    });

}
 
Example 8
Source File: ImportItem.java    From apkextractor with GNU General Public License v3.0 4 votes vote down vote up
public ImportItem(@NonNull Context context,@NonNull FileItem fileItem){
    this.fileItem=fileItem;
    this.context=context;
    version_name=context.getResources().getString(R.string.word_unknown);
    version_code=context.getResources().getString(R.string.word_unknown);
    minSdkVersion=context.getResources().getString(R.string.word_unknown);
    targetSdkVersion=context.getResources().getString(R.string.word_unknown);
    drawable=context.getResources().getDrawable(R.drawable.icon_file);
    if(fileItem.getName().trim().toLowerCase().endsWith(".zip")
            ||fileItem.getName().trim().toLowerCase().endsWith(SPUtil.getCompressingExtensionName(context).toLowerCase())){
        importType=ImportType.ZIP;
        drawable=context.getResources().getDrawable(R.drawable.icon_zip);
    }
    if(fileItem.getName().trim().toLowerCase().endsWith(".xapk")){
        importType=ImportType.ZIP;
        drawable=context.getResources().getDrawable(R.drawable.icon_xapk);
    }
    if(fileItem.getName().trim().toLowerCase().endsWith(".apk")){
        importType=ImportType.APK;
        PackageManager packageManager=context.getApplicationContext().getPackageManager();
        if(fileItem.isFileInstance()){
            try{
                int flag=0;
                final SharedPreferences settings=SPUtil.getGlobalSharedPreferences(context);
                if(settings.getBoolean(Constants.PREFERENCE_LOAD_PERMISSIONS,Constants.PREFERENCE_LOAD_PERMISSIONS_DEFAULT))flag|=PackageManager.GET_PERMISSIONS;
                if(settings.getBoolean(Constants.PREFERENCE_LOAD_ACTIVITIES,Constants.PREFERENCE_LOAD_ACTIVITIES_DEFAULT))flag|=PackageManager.GET_ACTIVITIES;
                if(settings.getBoolean(Constants.PREFERENCE_LOAD_RECEIVERS,Constants.PREFERENCE_LOAD_RECEIVERS_DEFAULT))flag|=PackageManager.GET_RECEIVERS;
                if(settings.getBoolean(Constants.PREFERENCE_LOAD_APK_SIGNATURE,Constants.PREFERENCE_LOAD_APK_SIGNATURE_DEFAULT))flag|=PackageManager.GET_SIGNATURES;
                if(settings.getBoolean(Constants.PREFERENCE_LOAD_SERVICES,Constants.PREFERENCE_LOAD_SERVICES_DEFAULT))flag|=PackageManager.GET_SERVICES;
                if(settings.getBoolean(Constants.PREFERENCE_LOAD_PROVIDERS,Constants.PREFERENCE_LOAD_PROVIDERS_DEFAULT))flag|=PackageManager.GET_PROVIDERS;
                packageInfo=packageManager.getPackageArchiveInfo(fileItem.getPath(),flag);
            }catch (Exception e){e.printStackTrace();}
            if(packageInfo!=null){
                packageInfo.applicationInfo.sourceDir=fileItem.getPath();
                packageInfo.applicationInfo.publicSourceDir=fileItem.getPath();
                drawable=packageInfo.applicationInfo.loadIcon(packageManager);
                version_name=packageInfo.versionName;
                version_code=String.valueOf(packageInfo.versionCode);
                if(Build.VERSION.SDK_INT>23){
                    minSdkVersion=String.valueOf(packageInfo.applicationInfo.minSdkVersion);
                }
                targetSdkVersion=String.valueOf(packageInfo.applicationInfo.targetSdkVersion);
            }else{
                drawable=context.getResources().getDrawable(R.drawable.icon_apk);

            }
        }else{
            drawable=context.getResources().getDrawable(R.drawable.icon_apk);
        }

    }
    length=fileItem.length();
    lastModified =fileItem.lastModified();
}
 
Example 9
Source File: ApkTargetMapping.java    From GPT with Apache License 2.0 4 votes vote down vote up
/**
 * getPackageArchiveInfo
 *
 * @param parser          android.content.pm.PackageParser
 * @param pkg             PackageParser.Package
 * @param archiveFilePath archiveFilePath
 * @param flags           flags
 * @return PackageInfo
 */
public PackageInfo getPackageArchiveInfo(android.content.pm.PackageParser parser, PackageParser.Package pkg,
                                         String archiveFilePath, int flags) {
    PackageInfo packageInfo = null;
    if ((flags & PackageManager.GET_SIGNATURES) != 0) {
        // 2.3 4.0 4.1 4.2 4.4
        parser.collectCertificates(pkg, 0);
        // 5.0
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            parser.collectManifestDigest(pkg);
        }
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        // 4.2 4.3 4.4 5.0 6.0
        PackageUserState state = new PackageUserState();
        //packageInfo = PackageParser.generatePackageInfo(pkg, null, flags, 0, 0, null, state);
        try {
            // 这里使用反射。因为 permission 参数 在 5.0 5.1 6.0 上参数不同,但是我们传入的为 null
            packageInfo = JavaCalls.callStaticMethodOrThrow(PackageParser.class, "generatePackageInfo",
                    pkg, null, flags, 0L, 0L, null, state);
        } catch (Exception e) {
            if (Constants.DEBUG) {
                e.printStackTrace();
            }
            String methodInfo = JavaCalls
                    .getMethodToString(JavaCalls.getMethodFromClass(PackageParser.class, "generatePackageInfo"));
            if (methodInfo == null) {
                methodInfo = "";
            }
            throw new RuntimeException("generatePackageInfo get exception, " + methodInfo, e);
        }
    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        // 4.1
        packageInfo = PackageParser.generatePackageInfo(pkg, null, flags, 0, 0, null, false, 0);
    } else if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
        //  2.3 4.0
        packageInfo = PackageParser.generatePackageInfo(pkg, null, flags, 0, 0);
    }

    return packageInfo;
}
 
Example 10
Source File: PluginManagerServer.java    From springreplugin with Apache License 2.0 4 votes vote down vote up
private PluginInfo installLocked(String path) {
    final boolean verifySignEnable = RePlugin.getConfig().getVerifySign();
    final int flags = verifySignEnable ? PackageManager.GET_META_DATA | PackageManager.GET_SIGNATURES : PackageManager.GET_META_DATA;

    // 1. 读取APK内容
    PackageInfo pi = mContext.getPackageManager().getPackageArchiveInfo(path, flags);
    if (pi == null) {
        if (LogDebug.LOG) {
            LogDebug.e(TAG, "installLocked: Not a valid apk. path=" + path);
        }

        RePlugin.getConfig().getEventCallbacks().onInstallPluginFailed(path, RePluginEventCallbacks.InstallResult.READ_PKG_INFO_FAIL);
        return null;
    }

    // 2. 校验插件签名
    if (verifySignEnable) {
        if (!verifySignature(pi, path)) {
            return null;
        }
    }

    // 3. 解析出名字和三元组
    PluginInfo instPli = PluginInfo.parseFromPackageInfo(pi, path);
    if (LogDebug.LOG) {
        LogDebug.i(TAG, "installLocked: Info=" + instPli);
    }
    instPli.setType(PluginInfo.TYPE_NOT_INSTALL);

    // 若要安装的插件版本小于或等于当前版本,则安装失败
    // NOTE 绝大多数情况下,应该在调用RePlugin.install方法前,根据云端回传的信息来判断,以防止下载旧插件,浪费流量
    // NOTE 这里仅做双保险,或通过特殊渠道安装时会有用

    // 注意:这里必须用“非Clone过的”PluginInfo,因为要修改里面的内容
    PluginInfo curPli = RePluginOS.getPlugin(instPli.getName(), false);
    if (curPli != null) {
        if (LogDebug.LOG) {
            LogDebug.i(TAG, "installLocked: Has installed plugin. current=" + curPli);
        }

        // 版本较老?直接返回
        final int checkResult = checkVersion(instPli, curPli);
        if (checkResult < 0) {
            RePlugin.getConfig().getEventCallbacks().onInstallPluginFailed(path, RePluginEventCallbacks.InstallResult.VERIFY_VER_FAIL);
            return null;
        } else if (checkResult == 0){
            instPli.setIsPendingCover(true);
        }
    }

    // 4. 将合法的APK改名后,移动(或复制,见RePluginConfig.isMoveFileWhenInstalling)到新位置
    // 注意:不能和p-n的最终释放位置相同,因为管理方式不一样
    if (!copyOrMoveApk(path, instPli)) {
        RePlugin.getConfig().getEventCallbacks().onInstallPluginFailed(path, RePluginEventCallbacks.InstallResult.COPY_APK_FAIL);
        return null;
    }

    // 5. 从插件中释放 So 文件
    PluginNativeLibsHelper.install(instPli.getPath(), instPli.getNativeLibsDir());

    // 6. 若已经安装旧版本插件,则尝试更新插件信息,否则直接加入到列表中
    if (curPli != null) {
        updateOrLater(curPli, instPli);
    } else {
        mList.add(instPli);
    }

    // 7. 保存插件信息到文件中,下次可直接使用
    mList.save(mContext);

    return instPli;
}
 
Example 11
Source File: APPUtil.java    From DownloadManager with Apache License 2.0 4 votes vote down vote up
/**
 * 获取未安装APK的签名, 由于市面上的Android系统版本各一,不推荐使用这种方法获取应用签名
 * @param apkPath
 * @return
 */
public static String getUninstallAPKSignatures(String apkPath) {  
	//参数列表类型
	Class[] typeArgs = new Class[1];   
	//参数列表值
	Object[] valueArgs = new Object[1];   
       try {   
           //2.这是一个Package 解释器, 是隐藏的,获取PackageParser的类
           Class pkgParserCls = Class.forName("android.content.pm.PackageParser");  
           
           //2.创建PackageParser的实例
           typeArgs[0] = String.class;   
           Constructor pkgParserCt = pkgParserCls.getConstructor(typeArgs);   
           valueArgs[0] = apkPath;   
           Object pkgParser = pkgParserCt.newInstance(valueArgs);   
           
           //3.获取PackageParser的类的  parsePackage方法;PackageParser.Package mPkgInfo = packageParser.parsePackage(new File(apkPath), apkPath, metrics, 0);   
           typeArgs = new Class[4];   
           typeArgs[0] = File.class;   
           typeArgs[1] = String.class;   
           typeArgs[2] = DisplayMetrics.class;   
           typeArgs[3] = int.class;   
           Method pkgParser_parsePackageMtd = pkgParserCls.getDeclaredMethod("parsePackage", typeArgs);   
           
           //4.执行parsePackage方法
           valueArgs = new Object[4];   
           valueArgs[0] = new File(apkPath);   
           valueArgs[1] = apkPath;   
           DisplayMetrics metrics = new DisplayMetrics();   
           metrics.setToDefaults(); 
           valueArgs[2] = metrics;   
           valueArgs[3] = PackageManager.GET_SIGNATURES;   
           Object pkgParserPkg = pkgParser_parsePackageMtd.invoke(pkgParser, valueArgs);   
            
           //5.获取PackageParser类的collectCertificates方法
           typeArgs = new Class[2];   
           typeArgs[0] = pkgParserPkg.getClass();   
           typeArgs[1] = int.class;   
           Method pkgParser_collectCertificatesMtd = pkgParserCls.getDeclaredMethod("collectCertificates", typeArgs); 
           
           //6.执行collectCertificates方法
           valueArgs = new Object[2];   
           valueArgs[0] = pkgParserPkg;   
           valueArgs[1] = PackageManager.GET_SIGNATURES;   
           pkgParser_collectCertificatesMtd.invoke(pkgParser, valueArgs);   
           
           //7.获取PackageParser.Package的类的mSignatures属性
           Field packageInfoFld = pkgParserPkg.getClass().getDeclaredField("mSignatures");  
           
           //8.获取PackageParser.Package的类的mSignatures属性的值
           Signature[] info = (Signature[]) packageInfoFld.get(pkgParserPkg);   
           return info[0].toCharsString();   
       } catch (Exception e) {   
           e.printStackTrace();   
       }   
       return null;   
   }
 
Example 12
Source File: PluginClientManager.java    From AndroidPlugin with MIT License 4 votes vote down vote up
/**
 * add a apk client. Before start a plugin Activity, we should do this
 * first.<br/>
 * NOTE : will only be called by host apk.
 * 
 * @param dexPath
 */
public PluginClientInfo addPluginClient(String dexPath) {
	// when loadApk is called by host apk, we assume that plugin is invoked
	// by host.
	PackageManager packageManager = mContext.getPackageManager();

	int flags = PackageManager.GET_ACTIVITIES
			| PackageManager.GET_CONFIGURATIONS
			| PackageManager.GET_INSTRUMENTATION
			| PackageManager.GET_PERMISSIONS | PackageManager.GET_PROVIDERS
			| PackageManager.GET_RECEIVERS | PackageManager.GET_SERVICES
			| PackageManager.GET_SIGNATURES;

	PackageInfo packageInfo = packageManager.getPackageArchiveInfo(dexPath,
			flags);
	if (packageInfo == null) {
		return null;
	}

       final String packageName = packageInfo.packageName;
       PluginClientInfo pluginPackage = mPluginClientPackages.get(packageName);
       if (pluginPackage == null) {
           DexClassLoader dexClassLoader = null;
           if (mPluginClientDexClassLoaders.containsKey(packageName)) {
               dexClassLoader = mPluginClientDexClassLoaders.get(packageName);
           } else {
               dexClassLoader = createDexClassLoader(dexPath,
                       packageInfo.packageName, packageInfo.versionName);
               mPluginClientDexClassLoaders.put(packageName, dexClassLoader);
           }

           AssetManager assetManager = createAssetManager(dexPath);
           Resources resources = createResources(assetManager);
           pluginPackage = new PluginClientInfo(packageName, dexPath,
                   dexClassLoader, assetManager, resources, packageInfo);
           mPluginClientPackages.put(packageName, pluginPackage);
       }
       if (!mPluginClientDexPaths.containsKey(packageName)) {
           mPluginClientDexPaths.put(packageName, dexPath);
       }
       return pluginPackage;
   }
 
Example 13
Source File: PluginManagerImpl.java    From koala--Android-Plugin-Runtime- with Apache License 2.0 4 votes vote down vote up
/**
 * 解析APK的manifest
 * 
 * @param info
 *            插件信息
 */
private void getPackageInfo(PluginInfo info) {

    int flags = PackageManager.GET_ACTIVITIES | PackageManager.GET_CONFIGURATIONS
            | PackageManager.GET_INSTRUMENTATION | PackageManager.GET_PERMISSIONS | PackageManager.GET_PROVIDERS
            | PackageManager.GET_RECEIVERS | PackageManager.GET_SERVICES | PackageManager.GET_SIGNATURES;

    // 需要获取Package对象,主要是处理隐式启动插件中的activity
    PackageParser parser = new PackageParser(info.apkPath);
    DisplayMetrics metrics = new DisplayMetrics();
    metrics.setToDefaults();
    File sourceFile = new File(info.apkPath);
    PackageParser.Package pack = parser.parsePackage(sourceFile, info.apkPath, metrics, 0);

    // 因为PackagePaser的generatePackageInfo方法不同版本参数相差太多,所以还是用packagemanager的api
    // 但这样导致APK被解析了两次,上面获取Package是一次
    PackageInfo packageInfo = mContext.getPackageManager().getPackageArchiveInfo(info.apkPath, flags);

    info.packageName = packageInfo.packageName;
    info.mPackageObj = pack;
    info.mPackageInfo = packageInfo;

    ArrayList<PackageParser.Activity> activitys = pack.activities;
    int size = activitys.size();
    for (int i = 0; i < size; i++) {
        mActivitys.addActivity(activitys.get(i));
    }

    ArrayList<PackageParser.Service> services = pack.services;
    size = services.size();
    for (int i = 0; i < size; i++) {
        mServices.addService(services.get(i));
    }

    ArrayList<PackageParser.Provider> providers = pack.providers;
    size = providers.size();
    for (int i = 0; i < size; i++) {
        Provider p = providers.get(i);
        String names[] = PATTERN_SEMICOLON.split(p.info.authority);
        for (int j = 0; j < names.length; j++) {
            mProviderInfoMap.put(names[i], p);
        }
    }
}