美文网首页
在应用中打开一个新的app

在应用中打开一个新的app

作者: 曾经的追风少年 | 来源:发表于2017-03-13 16:09 被阅读0次

    根据包名,我们可以在应用中启动另一个app

    public class OpenAppUtils {
        /**
         * 根据包名切换到该应用
         */
        private static Intent getAppOpenIntentByPackageName(Context context, String packageName) {
            // MainActivity完整名
            String mainAct = null;
            // 根据包名寻找MainActivity
            PackageManager pkgMag = context.getPackageManager();
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            intent.setFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED | Intent.FLAG_ACTIVITY_NEW_TASK);
    
            List<ResolveInfo> list = pkgMag.queryIntentActivities(intent, PackageManager.GET_ACTIVITIES);
            for (int i = 0; i < list.size(); i++) {
                ResolveInfo info = list.get(i);
                if (info.activityInfo.packageName.equals(packageName)) {
                    mainAct = info.activityInfo.name;
                    break;
                }
            }
            if (TextUtils.isEmpty(mainAct)) {
                return null;
            }
            intent.setComponent(new ComponentName(packageName, mainAct));
            return intent;
        }
    
        private static Context getPackageContext(Context context, String packageName) {
            Context pkgContext = null;
            if (context.getPackageName().equals(packageName)) {
                pkgContext = context;
            } else {
                // 创建第三方应用的上下文环境
                try {
                    pkgContext = context.createPackageContext(packageName, Context.CONTEXT_IGNORE_SECURITY
                            | Context.CONTEXT_INCLUDE_CODE);
                } catch (PackageManager.NameNotFoundException e) {
                    e.printStackTrace();
                }
            }
            return pkgContext;
        }
    
        public static boolean openPackage(Context context, String packageName) {
            Context pkgContext = getPackageContext(context, packageName);
            Intent intent = getAppOpenIntentByPackageName(context, packageName);
            if (pkgContext != null && intent != null) {
                pkgContext.startActivity(intent);
                return true;
            }
            Toast.makeText(context,"没有安装该应用",Toast.LENGTH_SHORT).show();
            return false;
        }
    }
    

    相关文章

      网友评论

          本文标题:在应用中打开一个新的app

          本文链接:https://www.haomeiwen.com/subject/taxqnttx.html