0

I am trying to open up a chat with the phone number (phone) by default when a user clicks a button. but it is not starting at all.

case R.id.nav_chat:             
       PackageManager packageManager = getApplicationContext().getPackageManager();
       Intent whatsapp_intent = new Intent(android.content.Intent.ACTION_SEND);

       try {
             String phone = "123456789";
             String message = "Hello, can you help with my issues?";
             String url = "https://api.whatsapp.com/send?phone="+ phone +"&text=" + URLEncoder.encode(message, "UTF-8");
             whatsapp_intent.setPackage("com.whatsapp");
             whatsapp_intent.setData(Uri.parse(url));
             if (whatsapp_intent.resolveActivity(packageManager) != null) {
                 getApplication().startActivity(whatsapp_intent);
             }
        } catch (Exception e){
               e.printStackTrace();
        }
        break;
}

The answer to this question appears here originally https://stackoverflow.com/a/45821831/12632081

AouledIssa
  • 2,528
  • 2
  • 22
  • 39
chigirl
  • 69
  • 8

1 Answers1

0

You should set the Intent action as ACTION_VIEW and not ACTION_SEND

Intent whatsapp_intent = new Intent(android.content.Intent.ACTION_VIEW);

Also You should use the local Context and not the application context

//get it from your activity as `this` or from your fragment as: getActivity().getContext()
context.startActivity(whatsapp_intent); 
AouledIssa
  • 2,528
  • 2
  • 22
  • 39
  • thank you, will this method also work for email? like to programatically fill in a default address – chigirl Apr 14 '20 at 13:44
  • For email you will need a different Intent with action `ACTION_SEND` but it should work fine. Something to consider is that if you have more than one email client app android will prompt the user to chose. Here is a useful example hope it solves your problem: https://www.javatpoint.com/how-to-send-email-in-android-using-intent – AouledIssa Apr 14 '20 at 13:49