16

I followed this link and this is my code

Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("content://com.android.contacts/data/" + "MYNUMBER@s.whatsapp.net"));
                i.setPackage("com.whatsapp");
                startActivity(i);

This is my log

android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=content://com.android.contacts/data/MYNUMBER@s.whatsapp.net pkg=com.whatsapp }
        at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1545)
        at android.app.Instrumentation.execStartActivity(Instrumentation.java:1416)
        at android.app.Activity.startActivityForResult(Activity.java:3351)
        at android.app.Activity.startActivityForResult(Activity.java:3312)
        at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:824)
        at android.app.Activity.startActivity(Activity.java:3522)
        at android.app.Activity.startActivity(Activity.java:3490)
        at com.sieryuu.maidchan.MainActivity.onClick(MainActivity.java:61)
        at android.view.View.performClick(View.java:4147)
        at android.view.View$PerformClick.run(View.java:17161)
        at android.os.Handler.handleCallback(Handler.java:615)
        at android.os.Handler.dispatchMessage(Handler.java:92)
        at android.os.Looper.loop(Looper.java:213)
        at android.app.ActivityThread.main(ActivityThread.java:4787)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556)

My Question : How to send text to whatsapp contact in the background (without choose the contact number, I already know the ID)? Root if needed

Community
  • 1
  • 1
Sieryuu
  • 1,510
  • 2
  • 16
  • 41

7 Answers7

8

I found the right way to do this and is just simple after you read this article: http://howdygeeks.com/send-whatsapp-message-unsaved-number-android/

phone and message are both String.

Source code:

try {
            PackageManager packageManager = context.getPackageManager();
            Intent i = new Intent(Intent.ACTION_VIEW);
            String url = "https://api.whatsapp.com/send?phone="+ phone +"&text=" + URLEncoder.encode(message, "UTF-8");
            i.setPackage("com.whatsapp");
            i.setData(Uri.parse(url));
            if (i.resolveActivity(packageManager) != null) {
                context.startActivity(i);
            }
        } catch (Exception e){
            e.printStackTrace();
        }

Enjoy!

Crono
  • 2,024
  • 18
  • 16
3

If you want to send message to particular user in background without opening whatsapp and you have rooted device then use following code will help you,

 protected void whatsAppSendMessage(String[] paramArrayOfString, String paramString) {
  try {
   Shell shell = Shell.startRootShell();
   int j = paramArrayOfString.length;
   for (int i = 0; i < j; i++) {
    String str3;
    long l1;
    long l2;
    int k;
    String str1;
    String str2;
    Random localRandom = new Random(20L);

    Log.d("AUTO",
      "ps | grep -w 'com.whatsapp' | awk '{print $2}' | xargs kill");
    commandsTestOnClick("ps | grep -w 'com.whatsapp' | awk '{print $2}' | xargs kill");

    str3 = paramArrayOfString[i] + "@s.whatsapp.net";
    l1 = System.currentTimeMillis();
    l2 = l1 / 1000L;
    k = localRandom.nextInt();

    str1 = "sqlite3 /data/data/com.whatsapp/databases/msgstore.db \"INSERT INTO messages (key_remote_jid, key_from_me, key_id, status, needs_push, data, timestamp, MEDIA_URL, media_mime_type, media_wa_type, MEDIA_SIZE, media_name , latitude, longitude, thumb_image, remote_resource, received_timestamp, send_timestamp, receipt_server_timestamp, receipt_device_timestamp, raw_data, media_hash, recipient_count, media_duration, origin)VALUES ('"
      + str3
      + "', 1,'"
      + l2
      + "-"
      + k
      + "', 0,0, '"
      + paramString
      + "',"
      + l1
      + ",'','', '0', 0,'', 0.0,0.0,'','',"
      + l1
      + ", -1, -1, -1,0 ,'',0,0,0); \"";

    str2 = "sqlite3 /data/data/com.whatsapp/databases/msgstore.db \"insert into chat_list (key_remote_jid) select '"
      + str3
      + "' where not exists (select 1 from chat_list where key_remote_jid='"
      + str3 + "');\"";

    str3 = "sqlite3 /data/data/com.whatsapp/databases/msgstore.db \"update chat_list set message_table_id = (select max(messages._id) from messages) where chat_list.key_remote_jid='"
      + str3 + "';\"";

    Log.d("AUTO", str1);
    Log.d("AUTO", str2);
    Log.d("AUTO", str3);

    shell.add(
      new SimpleCommand(
        "chmod 777 /data/data/com.whatsapp/databases/msgstore.db"))
      .waitForFinish();
    shell.add(new SimpleCommand(str1)).waitForFinish();
    shell.add(new SimpleCommand(str2)).waitForFinish();
    shell.add(new SimpleCommand(str3)).waitForFinish();
   }
   shell.close();
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

Just check it out this blog for more information... I have tested it is working successfully

http://siddhpuraamit.blogspot.in/

Siddhpura Amit
  • 14,534
  • 16
  • 91
  • 150
2

after googling a little, i found the following code

    public void onClickWhatsApp(View view) {

    Intent waIntent = new Intent(Intent.ACTION_SEND);
    waIntent.setType("text/plain");
            String text = "YOUR TEXT HERE";
    waIntent.setPackage("com.whatsapp");
    if (waIntent != null) {
        waIntent.putExtra(Intent.EXTRA_TEXT, text);//
        startActivity(Intent.createChooser(waIntent, "Share with"));
    } else {
        Toast.makeText(this, "WhatsApp not Installed", Toast.LENGTH_SHORT)
                .show();
    }

}

so you can send an intent to send a message, but as far is ive read you cant send it to a specific contact

Ahmed Ekri
  • 4,601
  • 3
  • 23
  • 42
Daniel Bo
  • 2,518
  • 1
  • 18
  • 29
  • 2
    That code is showing chooser. What I want is send to specific contact in the background. – Sieryuu Sep 21 '13 at 11:24
  • as you can access whatsapp only via intent for activities, its has to happen in foreground since there is no api for it. i guess its to prevent other apps from communicating using their backend infrastructure – Daniel Bo Sep 21 '13 at 11:49
  • But I wonder how people can make the API with `PHP` and `Python`, so I think I should be possible – Sieryuu Sep 22 '13 at 08:46
  • 2
    The people who made the api had to reverse engineer the library in order to get it to work (https://github.com/venomous0x/WhatsAPI). If you want to send a message in the background, I think you will need to pass a message to your server who will do it for you. – rarp Sep 22 '13 at 09:59
  • @RahulParsani Thanks, your comment sounds working.. Is there any working example? – Sieryuu Sep 25 '13 at 02:57
  • 1
    @Sieryuu I found [this](http://blog.philippheckel.com/2013/07/07/send-whatsapp-messages-via-php-script-using-whatsapi/) an also the source code has whatsapp.php under the tests folder. You can look at both for ideas. Since you also mentioned python, I think the library to use would be https://github.com/tgalal/yowsup – rarp Sep 25 '13 at 03:06
2
private void openWhatsApp(String id) {

Cursor c = getSherlockActivity().getContentResolver().query(ContactsContract.Data.CONTENT_URI,
        new String[] { ContactsContract.Contacts.Data._ID }, ContactsContract.Data.DATA1 + "=?",
        new String[] { id }, null);
c.moveToFirst();
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("content://com.android.contacts/data/" + c.getString(0)));

startActivity(i);
c.close();
}

Where id is what's app uri like

 0987654321@s.whatsapp.net
Ahmed Ekri
  • 4,601
  • 3
  • 23
  • 42
2

Try using the following solution,for image along with text.

Just change setType("text") and remove ExtraStream if you want to send text message only.

            Intent sendIntent = new Intent("android.intent.action.SEND");
            File f=new File("path to the file");
            Uri uri = Uri.fromFile(f);
            sendIntent.setComponent(new ComponentName("com.whatsapp","com.whatsapp.ContactPicker"));
            sendIntent.setType("image");
            sendIntent.putExtra(Intent.EXTRA_STREAM,uri);
            sendIntent.putExtra("jid", PhoneNumberUtils.stripSeparators("919xxxxxxxxx")+"@s.whatsapp.net");
            sendIntent.putExtra(Intent.EXTRA_TEXT,"sample text you want to send along with the image");
            startActivity(sendIntent);

EXTRA INFORMATION ABOUT THE PROCESS OF FINDING THE SOLUTION :

After reverse engineering WhatsApp, I came across the following snippet of Android manifest,

Normal Share intent, uses "SEND" which does not allow you to send to a specific contact and requires a contact picker.

The specific contact is picked up by Conversation class and uses "SEND_TO" action, but it uses sms body and can not take up image and other attachments.

 <activity android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|screenSize|smallestScreenSize|uiMode" android:name="com.whatsapp.Conversation" android:theme="@style/Theme.App.CondensedActionBar" android:windowSoftInputMode="stateUnchanged">
            <intent-filter>
                <action android:name="android.intent.action.SENDTO"/>
                <category android:name="android.intent.category.DEFAULT"/>
                <category android:name="android.intent.category.BROWSABLE"/>
                <data android:scheme="sms"/>
                <data android:scheme="smsto"/>
            </intent-filter>
        </activity>

Digging further, I came across this,

 <activity android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|screenSize|smallestScreenSize|uiMode" android:name="com.whatsapp.ContactPicker" android:theme="@style/Theme.App.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.PICK"/>
                <category android:name="android.intent.category.DEFAULT"/>
                <category android:name="com.whatsapp"/>
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.SEND"/>
                <category android:name="android.intent.category.DEFAULT"/>
                <data android:mimeType="audio/*"/>
                <data android:mimeType="video/*"/>
                <data android:mimeType="image/*"/>
                <data android:mimeType="text/plain"/>
                <data android:mimeType="text/x-vcard"/>
                <data android:mimeType="application/pdf"/>
                <data android:mimeType="application/vnd.openxmlformats-officedocument.wordprocessingml.document"/>
                <data android:mimeType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"/>
                <data android:mimeType="application/vnd.openxmlformats-officedocument.presentationml.presentation"/>
                <data android:mimeType="application/msword"/>
                <data android:mimeType="application/vnd.ms-excel"/>
                <data android:mimeType="application/vnd.ms-powerpoint"/>
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.SEND_MULTIPLE"/>
                <category android:name="android.intent.category.DEFAULT"/>
                <data android:mimeType="audio/*"/>
                <data android:mimeType="video/*"/>
                <data android:mimeType="image/*"/>
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.VIEW"/>
                <category android:name="android.intent.category.DEFAULT"/>
                <category android:name="android.intent.category.BROWSABLE"/>
                <data android:host="send" android:scheme="whatsapp"/>
            </intent-filter>
            <meta-data android:name="android.service.chooser.chooser_target_service" android:value=".ContactChooserTargetService"/>
        </activity>

Finally using a decompiler for ContactPicker and Conversation class,the extra key-value for phone number was found to be "jid".

Bhavita Lalwani
  • 903
  • 1
  • 9
  • 19
0

Try following:

Intent i = new Intent(Intent.ACTION_VIEW).setData(Uri.parse("content://com.android.contacts/data/" + "MYNUMBER@s.whatsapp.net"));
i.setPackage("com.whatsapp");
startActivity(i);
Erdinc Ay
  • 3,224
  • 4
  • 27
  • 42
  • I have tried it before, but the program crash. Have you test it? It works for you? – Sieryuu Sep 28 '13 at 01:03
  • have seen this in a book, he sets the uri via setData, thought that it might be helpful, currently i didnt have the environment for testing – Erdinc Ay Oct 01 '13 at 07:21
  • Where I should put the text I want to send? – Sieryuu Oct 01 '13 at 08:12
  • try: setResult( RESULT_OK, result ); this is usally used for sending back an OK or something like this, ... if you really want to send something else, than you have to lookup the WhatsApp classes, there should be classes that derive from Intent and can handle user data, for example a message – Erdinc Ay Oct 01 '13 at 08:17
  • I got this error `android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=content://com.android.contacts/data/MYNUMBER@s.whatsapp.net pkg=com.whatsapp }` – Sieryuu Oct 01 '13 at 15:22
  • I'll write it down here, if I find a solution. kr – Erdinc Ay Oct 07 '13 at 07:37
  • @SWAppDev there is only a small chance to do this, but I had not time to look it up. kr – Erdinc Ay Nov 24 '15 at 11:30
-1

You can try this, it works for me:

String waUrl = "https://wa.me/918982061674?text=I+can+help+you+with+your+BA+Tuition+requirement.+Please+call+me+at+09080976510+or+check+my+UrbanPro+profile%3A+http%3A%2F%2Flocalhost%3A8080%2Ftesturl";

try {
  PackageManager packageManager = context.getPackageManager();
  Intent i = new Intent(Intent.ACTION_VIEW);
  String url = waUrl;
  i.setPackage("com.whatsapp");
  i.setData(Uri.parse(url));
  if (i.resolveActivity(packageManager) != null) {
    context.startActivity(i);
  }
} catch (Exception e) {
  Log.e("WHATSAPP", e.getMessage())
}
Federico Grandi
  • 6,785
  • 5
  • 30
  • 50
Aakash Daga
  • 1,433
  • 10
  • 7