1

I found some code for sending message through whatsapp. Something like this:

    Button send=(Button)findViewById(R.id.sendbtn);
    EditText input=(EditText)findViewById(R.id.inputtxt);
    final String txt=input.getText().toString();

    send.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent sendIntent=new Intent();
            sendIntent.setAction(Intent.ACTION_SEND);
            sendIntent.putExtra(Intent.EXTRA_TEXT,txt);
            sendIntent.setType("text/plain");
            sendIntent.setPackage("com.whatsapp");
            startActivity(sendIntent);



        }
    });`

The code is working but when the whatsapp screen shows up and i select a contact, my whatsapp closes and my application shows up. Is there anything else to be added to send a message?

Kyle
  • 13
  • 1
  • 6

2 Answers2

1

what you did is correct, according to https://www.whatsapp.com/faq/android/28000012

It opens whatsapp and let you select the contact to send the message to

Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
sendIntent.setType("text/plain");sendIntent.setPackage("com.whatsapp");
startActivity(sendIntent);

alternatively, you can also select a contact, and then whatapps will open with the contact selected. you can then add the text in yourself from that window.

see the answer for this question: How do I open conversation of a particular contact in Whatsapp

what you cannot do is to use an intent to send a message to a specific contact directly from your app. (I assume it is an anti-spam decision on whatsapp's part).

Community
  • 1
  • 1
Angel Koh
  • 12,479
  • 7
  • 64
  • 91
1

Try below changed code :

Button send=(Button)findViewById(R.id.sendbtn);
EditText input=(EditText)findViewById(R.id.inputtxt);


send.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        final String txt = input.getText().toString();

        Intent sendIntent=new Intent();
        sendIntent.setAction(Intent.ACTION_SEND);
        sendIntent.putExtra(Intent.EXTRA_TEXT,txt);
        sendIntent.setType("text/plain");
        sendIntent.setPackage("com.whatsapp");
        startActivity(sendIntent);



    }
});`
Vickyexpert
  • 3,147
  • 5
  • 21
  • 34