Android 打开另一个app的两种方式

时间:2025-01-26 22:30:17
//打开外部app,新窗口打开 private void doStartApplicationWithPackageName(String packagename) { // 通过包名获取此APP详细信息,包括Activities、services、versioncode、name等等 PackageInfo packageinfo = null; try { packageinfo = getPackageManager().getPackageInfo(packagename, 0); } catch ( e) { (); } if (packageinfo == null) { BDToast.showToast(getText(.app_not_found).toString()); return; } Intent resolveIntent = getPackageManager().getLaunchIntentForPackage(packagename);// 这里的packname就是从上面得到的目标apk的包名 startActivity(resolveIntent);// 启动目标应用 }
//打开外部app,嵌入旧窗口中
private void doStartApplicationWithPackageName(String packagename) {
    // 通过包名获取此APP详细信息,包括Activities、services、versioncode、name等等
    PackageInfo packageinfo = null;
    try {
        packageinfo = getPackageManager().getPackageInfo(packagename, 0);
    } catch ( e) {
        ();
    }
    if (packageinfo == null) {
        BDToast.showToast(getText(.app_not_found).toString());
        return;
    }

    // 创建一个类别为CATEGORY_LAUNCHER的该包名的Intent
    Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
    (Intent.CATEGORY_LAUNCHER);
    (packageinfo.packageName);

    // 通过getPackageManager()的queryIntentActivities方法遍历
    List<ResolveInfo> resolveinfoList = getPackageManager()
            .queryIntentActivities(resolveIntent, 0);

    ResolveInfo resolveinfo = ().next();
    if (resolveinfo != null) {
        // packagename = 参数packname
        String packageName = resolveinfo.activityInfo.packageName;
        // 这个就是我们要找的该APP的LAUNCHER的Activity[组织形式:]
        String className = resolveinfo.activityInfo.name;
        // LAUNCHER Intent
        Intent intent = new Intent(Intent.ACTION_MAIN);
        (Intent.CATEGORY_LAUNCHER);

        // 设置ComponentName参数1:packagename参数2:MainActivity路径
        ComponentName cn = new ComponentName(packageName, className);

        (cn);
        startActivity(intent);
    }
}