android 安装 APK

来源:互联网 发布:神经网络算法matlab 编辑:程序博客网 时间:2024/06/03 18:08

安装APK:

public static void installApp(Context context, String packageName) {        try {            PackageInfo pi = context.getPackageManager().getPackageInfo(packageName, 0);            Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);            resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);            resolveIntent.setPackage(pi.packageName);            List<ResolveInfo> apps = context.getPackageManager().queryIntentActivities(resolveIntent, 0);            if (!apps.isEmpty()) {                ResolveInfo ri = apps.get(0);                Intent intent = new Intent(Intent.ACTION_MAIN);                intent.addCategory(Intent.CATEGORY_LAUNCHER);                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);                intent.setComponent(new ComponentName(ri.activityInfo.packageName, ri.activityInfo.name));                context.startActivity(intent);            }        } catch (NameNotFoundException e) {            // no-op        }    }


一些用到的细节:

Intent的setPackage 可以限制 Intent只能投递到某个Package内的Component.

/**     * (Usually optional) Set an explicit application package name that limits     * the components this Intent will resolve to.  If left to the default     * value of null, all components in all applications will considered.     * If non-null, the Intent can only match the components in the given     * application package.     *     * @param packageName The name of the application package to handle the     * intent, or null to allow any application package.     *     * @return Returns the same Intent object, for chaining multiple calls     * into a single statement.     *     * @see #getPackage     * @see #resolveActivity     */    public Intent setPackage(String packageName) {}

Intent的setComponent则限制Intent只能投递给某个Component, 和setClass干的事情一样,setClass的注释也说了:
 * Convenience for calling {@link #setComponent(ComponentName)} with the
 * name returned by a {@link Class} object.


ResolveInfo内部封装了对Intent解析<通过queryIntentActivities>出来的相关的Activity的info:ActivityInfo


0 0