Opening whatsapp through intent not working in Android 11

Viewed 9350

Opening Whatsapp with intent is not working in android OS 11 but working fine up to android (OS) 10 devices, It displays the message "Whatsapp app not installed in your phone" on the android 11 device. Does anyone have a solution for this?

String contact = "+91 9999999999"; // use country code with your phone number
        String url = "https://api.whatsapp.com/send?phone=" + contact;
        try {
            PackageManager pm = context.getPackageManager();
            pm.getPackageInfo("com.whatsapp", PackageManager.GET_ACTIVITIES);
            Intent i = new Intent(Intent.ACTION_VIEW);
            i.setData(Uri.parse(url));
            context.startActivity(i);
        } catch (PackageManager.NameNotFoundException e) {
          Toast.makeText(mContext, "Whatsapp app not installed in your phone",Toast.LENGTH_LONG).show();
           e.printStackTrace();
        }
4 Answers

There are new changes in android 11 of package visibility.
You need to add a new section queries under you app's <manifest> tag with desired package name:

<manifest package="com.example.app">
    <queries>
        <package android:name="com.whatsapp" />
    </queries>
  ...
</manifest>

"com.whatsapp"
can also be the culprit.

i was also boggled with this message.

the issue was "whatsApp business app" which has package name:
"com.whatsapp.w4b"

used following code to find out which one is installed:

String appPackage="";
if (isAppInstalled(ctx, "com.whatsapp.w4b")) {
    appPackage = "com.whatsapp.w4b";
    //do ...
} else if (isAppInstalled(ctx, "com.whatsapp")) {
    appPackage = "com.whatsapp";
    //do ...
} else {
    Toast.makeText(ctx, "whatsApp is not installed", Toast.LENGTH_LONG).show();
}

private boolean isAppInstalled(Context ctx, String packageName) {
    PackageManager pm = ctx.getPackageManager();
    boolean app_installed;
    try {
        pm.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES);
        app_installed = true;
    } catch (PackageManager.NameNotFoundException e) {
        app_installed = false;
    }
    return app_installed;
}

Instead of using wildcards, it's more explicit to add both package names:

<manifest package="com.example.app">
    <queries>
        <package android:name="com.whatsapp"/>
        <package android:name="com.whatsapp.w4b"/>
    </queries>
  ...
</manifest>

Rather than adding each Package names in , you can add:

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

to your AndroidManifest.xml file in your project. I was also bothering with the same, this permission allowed me to troubleshoot my issue/error.

Related