android 检查用户是否安装了Whats-App或Whats-App Business

ruarlubt  于 2023-03-28  发布在  Android
关注(0)|答案(2)|浏览(251)

我想在我的应用程序中启动活动之前检查一个条件.我想检查用户是否安装了传统的WhatsApp或WhatsApp业务.我检查这两个应用程序的包的名称.然而,我得到一个例外,尽管我已经有WhatsApp在我的手机上.
这是我用来检查包名的代码

private boolean isPackageInstalled(String packageName, PackageManager packageManager) {
        try {
            packageManager.getPackageInfo(packageName, 0);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }
    }

我在onCreate方法中使用这个方法

private void checkwhatsversion() {

        PackageManager pm = mainactivity.this.getPackageManager();
        boolean isInstalled1 = isPackageInstalled("com.whatsapp", pm);
        boolean isInstalled2 = isPackageInstalled("com.whatsapp.w4b", pm);

        if(isInstalled1) {
            button1.setVisibility(View.VISIBLE);
        }

        if (isInstalled2) {
            button2.setVisibility(View.VISIBLE);
        }


    }
cfh9epnr

cfh9epnr1#

我是这么做的:

private fun pickWhatsappPackageName(activity: Activity): String? {

        val w4bPackageName = "com.whatsapp.w4b"
        val wpPackageName = "com.whatsapp"

        var packageName: String? = w4bPackageName

        val pm = activity.packageManager
        try {
            pm.getPackageInfo(w4bPackageName,
                PackageManager.GET_ACTIVITIES)
        } catch (exWhatsappForBusiness: PackageManager.NameNotFoundException) {
            try {
                pm.getPackageInfo(wpPackageName,
                    PackageManager.GET_ACTIVITIES)
                packageName = "com.whatsapp"
            } catch (exWhatsapp: PackageManager.NameNotFoundException) {
                packageName = null
            }
        }

        return packageName
    }

如果用户安装了Whatsapp业务,它将返回业务包,否则它将返回通常的Whatsapp包,如果不存在则返回null。
希望有帮助。

vshtjzan

vshtjzan2#

如果您还没有尝试以下操作-

private boolean isPackageInstalled(String packageName, PackageManager packageManager) {
        try {
            packageManager.getPackageInfo(packageName, packageManager.GET_ACTIVITIES);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }
 }

快乐编码!

相关问题