'xamrin android visual studio 2019 community version for WhatsApp chat with button click on specific number

I want to add button in my app. when I click on the button this will redirect me to WhatsApp chat having that specific number and chat with that number. I have the following code but its not working :(

  public void Button1_Click(object sender, System.EventArgs e)
    {
        string phoneNumberWithCountryCode = "+9233623xxx";
        string message = "Hallo";

        StartActivity(new Intent(
            Intent.ActionView, Android.Net.Uri.Parse("https://api.whatsapp.com/send?phone=" + phoneNumberWithCountryCode + "&text=" + message)));
    }


Button button1 = FindViewById<Button>(Resource.Id.watsapp_op);

        
      button1.Click += (sender, e) => {
        

         Button1_Click(sender, e);


        };


Solution 1:[1]

I saw the working sample , it sets Package in Intent , so try the following code .

private void OpenWhatsApp(Activity activity, string number, string message)
    {

        try
        {
            PackageManager packageManager = activity.PackageManager;
            Intent i = new Intent(Intent.ActionView);
            String url = "https://api.whatsapp.com/send?phone=" + number + "&text=" + URLEncoder.Encode(message, "UTF-8");
            i.SetPackage("com.whatsapp");
            i.SetData(Uri.Parse(url));
            if (i.ResolveActivity(packageManager) != null)
            {
                activity.StartActivity(i);
            }
            else
            {
                //Error message
            }
        }
        catch (Exception e)
        {
            // exception
        }

    }

Update

Does the button on the current content view or not ?

You can see SetContentView(Resource.Layout.activity_main) in OnCreate method .

You have to ensure the button is placed in activity_main.xml , if the button is in another layout , you have to find the view first .

var view = LayoutInflater.Inflate(Resource.Layout.anotherlayout,null);
var button = view.FindViewById<Button>(Resource.Id.button);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1