Android gets the list of apps installed on the phone (adaptation)

permissions

<uses-permission
        android:name="android.permission.QUERY_ALL_PACKAGES"
        tools:ignore="QueryAllPackagesPermission" />

Add permissions to get all apps

get code

public static boolean hasApplication(Context context, String packageName) {
        PackageManager packageManager = context.getPackageManager();
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
            Intent intent = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER);
            List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_ALL);
            for (int i = 0,count=list.size(); i <count ; i++) {
                if(list.get(i).activityInfo.applicationInfo.packageName.equalsIgnoreCase(packageName)) {
                    return true;
                }
            }
        }else{
        //packageManager.queryIntentActivities(intent,0)
            //获取系统中安装的应用包的信息
            List<PackageInfo> listPackageInfo = packageManager.getInstalledPackages(0);
            for (int i = 0; i < listPackageInfo.size(); i++) {
                if (listPackageInfo.get(i).packageName.equalsIgnoreCase(packageName)) {
                    return true;
                }
            }
        }


        return false;


    }

The lower version of the mobile phone can also use the method in else

Intent intent = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER);
packageManager.queryIntentActivities(intent,0)

The action of the Intent is: Intent.ACTION_MAIN Do not pass this wrong.

Obtain the full class name of the startup page of the corresponding application through the package name

/**
     * 获取APP的启动类
     * @param context
     * @param packageName
     * @return
     */
    String getAppStartClass(Context context, String packageName) {
        PackageManager packageManager = context.getPackageManager();
        try {
            Intent intent = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER);
            List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.GET_ACTIVITIES);
            for (int i = 0,count=list.size(); i <count ; i++) {
                if (TextUtils.equals(list.get(i).activityInfo.packageName, packageName)) {
                    return list.get(i).activityInfo.name;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return "";
        }
    }

水平有限,如有问题欢迎评论区留言指正。

如果在高版本上有问题的话建议将Try setting targetSdkVersion to 26.

Follow me for more knowledge or contribution

623d17826c2cbd0a01e9a85008eb2ef0.jpeg

e404728dac71a5eff7397cec6d051eb6.jpeg

Guess you like

Origin blog.csdn.net/c6E5UlI1N/article/details/129311768