Send Text to Specific Contact Programmatically (Whatsapp)

Send text to specific contact programmatically (whatsapp)

This is now possible through the WhatsApp Business API. Only businesses may apply to use it. This is the only way to directly send messages to phone numbers, without any human interaction.

Sending normal messages is free. It looks like you need to host a MySQL database and the WhatsApp Business Client on your server.

How to send message to particular whatsapp contact programmatically using intent?

     Intent sendIntent = new Intent("android.intent.action.MAIN");
sendIntent.setComponent(new ComponentName("com.whatsapp","com.whatsapp.Conversation"));
sendIntent.putExtra("jid", PhoneNumberUtils.stripSeparators("YOUR_PHONE_NUMBER")+"@s.whatsapp.net");//phone number without "+" prefix

startActivity(sendIntent);

Update:

The aforementioned hack cannot be used to add any particular message, so here is the new approach. Pass the user mobile in international format here without any brackets, dashes or plus sign. Example: If the user is of India and his mobile number is 94xxxxxxxx , then international format will be 9194xxxxxxxx. Don't miss appending country code as a prefix in mobile number.

  private fun sendMsg(mobile: String, msg: String){
try {
val packageManager = requireContext().packageManager
val i = Intent(Intent.ACTION_VIEW)
val url =
"https://wa.me/$mobile" + "?text=" + URLEncoder.encode(msg, "utf-8")
i.setPackage("com.whatsapp")
i.data = Uri.parse(url)
if (i.resolveActivity(packageManager) != null) {
requireContext().startActivity(i)
}
} catch (e: Exception) {
e.printStackTrace()
}
}

Note: This approach works only with contacts added in user's Whatsapp
account.

How can I send message to specific contact through WhatsApp from my android app?

Try using Intent.EXTRA_TEXT instead of sms_body as your extra key. Per WhatsApp's documentation, this is what you have to use.

An example from their website:

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

Their example uses Intent.ACTION_SEND instead of Intent.ACTION_SENDTO, so I'm not sure if WhatsApp even supports sending directly to a contact via the intent system. Some quick testing should let you determine that.

Send message to specific contact in WhatsApp on android studio

you just have to perform the following code:

try {
Intent sendMsg = new Intent(Intent.ACTION_VIEW);
String url = "https://api.whatsapp.com/send?phone=" + "+92 1111111111" + "&text=" + URLEncoder.encode("Your Message to Contact Number", "UTF-8");
sendMsg.setPackage("com.whatsapp");
sendMsg.setData(Uri.parse(url));
if (sendMsg.resolveActivity(getPackageManager()) != null) {
startActivity(sendMsg);
}
} catch (Exception e) {
e.printStackTrace();
}

Phone number should be in correct format as I have passed like 92 for Country code and other 10 digits for your Phone number and you can also pass the message you want.

Send message via whatsapp programmatically

You can do that only using the Accessibility API of Android.

The idea is quite simple, you'll actually make Android perform the click on Whatsapp's send button.

So the flow will be:

  1. Send a regular message (with the intent you're currently using) with a suffix at the end of your message content such as "Sent by MY_APP".
  2. Once the text there, your accessibility service will be notified that the EditText of whatsapp is filled.
  3. If the suffix is present on the EditText of whatsapp, Your accessibility service will click on the send button. (this is to avoid performing actions as the user types in naturally a regular message).

Here's an example (which you'll have tweak if you wanna make it more restrictive):

public class WhatsappAccessibilityService extends AccessibilityService {

@Override
public void onAccessibilityEvent (AccessibilityEvent event) {
if (getRootInActiveWindow () == null) {
return;
}

AccessibilityNodeInfoCompat rootInActiveWindow = AccessibilityNodeInfoCompat.wrap (getRootInActiveWindow ());

// Whatsapp Message EditText id
List<AccessibilityNodeInfoCompat> messageNodeList = rootInActiveWindow.findAccessibilityNodeInfosByViewId ("com.whatsapp:id/entry");
if (messageNodeList == null || messageNodeList.isEmpty ()) {
return;
}

// check if the whatsapp message EditText field is filled with text and ending with your suffix (explanation above)
AccessibilityNodeInfoCompat messageField = messageNodeList.get (0);
if (messageField.getText () == null || messageField.getText ().length () == 0
|| !messageField.getText ().toString ().endsWith (getApplicationContext ().getString (R.string.whatsapp_suffix))) { // So your service doesn't process any message, but the ones ending your apps suffix
return;
}

// Whatsapp send button id
List<AccessibilityNodeInfoCompat> sendMessageNodeInfoList = rootInActiveWindow.findAccessibilityNodeInfosByViewId ("com.whatsapp:id/send");
if (sendMessageNodeInfoList == null || sendMessageNodeInfoList.isEmpty ()) {
return;
}

AccessibilityNodeInfoCompat sendMessageButton = sendMessageNodeInfoList.get (0);
if (!sendMessageButton.isVisibleToUser ()) {
return;
}

// Now fire a click on the send button
sendMessageButton.performAction (AccessibilityNodeInfo.ACTION_CLICK);

// Now go back to your app by clicking on the Android back button twice:
// First one to leave the conversation screen
// Second one to leave whatsapp
try {
Thread.sleep (500); // hack for certain devices in which the immediate back click is too fast to handle
performGlobalAction (GLOBAL_ACTION_BACK);
Thread.sleep (500); // same hack as above
} catch (InterruptedException ignored) {}
performGlobalAction (GLOBAL_ACTION_BACK);
}
}

Then create its definition in res -> xml -> whatsapp_service.xml:

<?xml version="1.0" encoding="utf-8"?>
<accessibility-service
xmlns:android="http://schemas.android.com/apk/res/android"
android:accessibilityEventTypes="typeWindowContentChanged"
android:packageNames="com.whatsapp"
android:accessibilityFeedbackType="feedbackSpoken"
android:notificationTimeout="100"
android:canRetrieveWindowContent="true"/>

Then declare it in your manifest:

<service
android:name=".services.WhatsappAccessibilityService"
android:label="Accessibility Service"
android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE">
<meta-data
android:name="android.accessibilityservice"
android:resource="@xml/whatsapp_service"/>

<intent-filter>
<action android:name="android.accessibilityservice.AccessibilityService"/>
</intent-filter>
</service>

And last thing, is to check if the accessibility services are enabled for your app or not, and redirect the user to the settings if not:

private boolean isAccessibilityOn (Context context, Class<? extends AccessibilityService> clazz) {
int accessibilityEnabled = 0;
final String service = context.getPackageName () + "/" + clazz.getCanonicalName ();
try {
accessibilityEnabled = Settings.Secure.getInt (context.getApplicationContext ().getContentResolver (), Settings.Secure.ACCESSIBILITY_ENABLED);
} catch (Settings.SettingNotFoundException ignored) { }

TextUtils.SimpleStringSplitter colonSplitter = new TextUtils.SimpleStringSplitter (":");

if (accessibilityEnabled == 1) {
String settingValue = Settings.Secure.getString (context.getApplicationContext ().getContentResolver (), Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
if (settingValue != null) {
colonSplitter.setString (settingValue);
while (colonSplitter.hasNext ()) {
String accessibilityService = colonSplitter.next ();

if (accessibilityService.equalsIgnoreCase (service)) {
return true;
}
}
}
}

return false;
}

which you'll call with:

if (!isAccessibilityOn (context, WhatsappAccessibilityService.class)) {
Intent intent = new Intent (Settings.ACTION_ACCESSIBILITY_SETTINGS);
context.startActivity (intent);
}

This is purely on the technical aspect of the solution.

Now, the ethical question of "should you do that?", I believe the answer is quite clear:

Except if you are targeting people with disabilities (which is the very purpose of the Accessibility API), you should probably NOT do that.

Android: How to send message programmatically by using WhatsApp, WeChat?

I got the Solution.. Here I am posting the answer so that it may help other people who may have same doubt..

For Share through any application...

public void sendAppMsg(View view) {

Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
String text = " message you want to share..";
// change with required application package

intent.setPackage("PACKAGE NAME OF THE APPLICATION");
if (intent != null) {
intent.putExtra(Intent.EXTRA_TEXT, text);//
startActivity(Intent.createChooser(intent, text));
} else {

Toast.makeText(this, "App not found", Toast.LENGTH_SHORT)
.show();
}
}

Note : change *PACKAGE NAME OF THE APPLICATION as per your requirement like

Example : USE

//Whatsapp
intent.setPackage("com.whatsapp");`

//Linkedin
intent.setPackage("com.linkedin.android");

//Twitter
intent.setPackage("com.twitter.android");

//Facebook
intent.setPackage("com.facebook.katana");

//GooglePlus
intent.setPackage("com.google.android.apps.plus");

Send message to particular contact through WhatsApp in android

I think you want like this.

private void openWhatsApp() {
String text = message.getText().toString();
if(whatsappInstalledOrNot("com.whatsapp")){
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("whatsapp://send?text="+text+"&phone="+mobileNumber.getText().toString()));
startActivity(browserIntent);
}else {
Toast.makeText(this, "WhatsApp not Installed", Toast.LENGTH_SHORT)
.show();
}
}
private boolean whatsappInstalledOrNot(String uri) {
PackageManager pm = getPackageManager();
boolean app_installed = false;
try {
pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
app_installed = true;
} catch (PackageManager.NameNotFoundException e) {
app_installed = false;
}
return app_installed;
}

Hope this will help.

Sending message through WhatsApp

UPDATE
Please refer to https://faq.whatsapp.com/en/android/26000030/?category=5245251

WhatsApp's Click to Chat feature allows you to begin a chat with
someone without having their phone number saved in your phone's
address book. As long as you know this person’s phone number, you can
create a link that will allow you to start a chat with them.

Use: https://wa.me/15551234567

Don't use: https://wa.me/+001-(555)1234567

Example: https://wa.me/15551234567?text=I'm%20interested%20in%20your%20car%20for%20sale

Original answer
Here is the solution

public void onClickWhatsApp(View view) {

PackageManager pm=getPackageManager();
try {

Intent waIntent = new Intent(Intent.ACTION_SEND);
waIntent.setType("text/plain");
String text = "YOUR TEXT HERE";

PackageInfo info=pm.getPackageInfo("com.whatsapp", PackageManager.GET_META_DATA);
//Check if package exists or not. If not then code
//in catch block will be called
waIntent.setPackage("com.whatsapp");

waIntent.putExtra(Intent.EXTRA_TEXT, text);
startActivity(Intent.createChooser(waIntent, "Share with"));

} catch (NameNotFoundException e) {
Toast.makeText(this, "WhatsApp not Installed", Toast.LENGTH_SHORT)
.show();
}

}

Also see http://www.whatsapp.com/faq/en/android/28000012



Related Topics



Leave a reply



Submit