I wanted to know how I can send text to a specific whatsapp contact. I found some code to view a specific contact, but not to send data.
Cursor c = 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();
This works fine for viewing a whatsapp-contact, but how can I add some text now? Or didn't the Whatsapp-developer implement such kind of an api?
I've found the right way to do this:
Source code: phone and message are both String.
PackageManager packageManager = context.getPackageManager();
Intent i = new Intent(Intent.ACTION_VIEW);
try {
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 yourself!
I think the answer is a mix of your question and this answer here: https://stackoverflow.com/a/15931345/734687
So I would try the following code:
change ACTION_VIEW to ACTION_SENDTO
set the Uri as you did
set the package to whatsapp
Intent i = new Intent(Intent.ACTION_SENDTO, Uri.parse("content://com.android.contacts/data/" + c.getString(0)));
i.setType("text/plain");
i.setPackage("com.whatsapp"); // so that only Whatsapp reacts and not the chooser
i.putExtra(Intent.EXTRA_SUBJECT, "Subject");
i.putExtra(Intent.EXTRA_TEXT, "I'm the body.");
startActivity(i);
I looked into the Whatsapp manifest and saw that ACTION_SEND is registered to the activity ContactPicker, so that will not help you. However ACTION_SENDTO is registered to the activity com.whatsapp.Conversation which sounds more adequate for your problem.
Whatsapp can work as a replacement for sending SMS, so it should work like SMS. When you do not specify the desired application (via setPackage) Android displays the application picker. Thererfor you should just look at the code for sending SMS via intent and then provide the additional package information.
Uri uri = Uri.parse("smsto:" + smsNumber);
Intent i = new Intent(Intent.ACTION_SENDTO, uri);
i.putExtra("sms_body", smsText);
i.setPackage("com.whatsapp");
startActivity(i);
First try just to replace the intent ACTION_SEND to ACTION_SENDTO . If this does not work than provide the additional extra sms_body. If this does not work than try to change the uri.
Update
I tried to solve this myself and was not able to find a solution. Whatsapp is opening the chat history, but doesn't take the text and send it. It seems that this functionality is just not implemented.
I have done it!
private void openWhatsApp() {
String smsNumber = "7****"; // E164 format without '+' sign
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.setType("text/plain");
sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
sendIntent.putExtra("jid", smsNumber + "#s.whatsapp.net"); //phone number without "+" prefix
sendIntent.setPackage("com.whatsapp");
if (intent.resolveActivity(getActivity().getPackageManager()) == null) {
Toast.makeText(this, "Error/n" + e.toString(), Toast.LENGTH_SHORT).show();
return;
}
startActivity(sendIntent);
}
This approach works with WhatsApp Business app as well!
Change package name as sendIntent.setPackage("com.whatsapp.w4b"); for WhatsApp Business.
Great hack Rishabh, thanks a lot, I was looking for this solution since last 3 years.
As per the Rishabh Maurya's answer above, I have implemented this code which is working fine for both text and image sharing on WhatsApp.
Note that in both the cases it opens a whatsapp conversation (if toNumber exists in users whatsapp contact list), but user have to click send button to complete the action. That means it helps in skipping contact selection step.
For text messages
String toNumber = "+91 98765 43210"; // contains spaces.
toNumber = toNumber.replace("+", "").replace(" ", "");
Intent sendIntent = new Intent("android.intent.action.MAIN");
sendIntent.putExtra("jid", toNumber + "#s.whatsapp.net");
sendIntent.putExtra(Intent.EXTRA_TEXT, message);
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.setPackage("com.whatsapp");
sendIntent.setType("text/plain");
startActivity(sendIntent);
For sharing images
String toNumber = "+91 98765 43210"; // contains spaces.
toNumber = toNumber.replace("+", "").replace(" ", "");
Intent sendIntent = new Intent("android.intent.action.MAIN");
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(imageFile));
sendIntent.putExtra("jid", toNumber + "#s.whatsapp.net");
sendIntent.putExtra(Intent.EXTRA_TEXT, message);
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.setPackage("com.whatsapp");
sendIntent.setType("image/png");
context.startActivity(sendIntent);
Enjoy WhatsApping!
It lets you open WhatsApp conversation screen for that specific user you are trying to communicate with:
private void openWhatsApp() {
String smsNumber = "91XXXXXXXX20";
boolean isWhatsappInstalled = whatsappInstalledOrNot("com.whatsapp");
if (isWhatsappInstalled) {
Intent sendIntent = new Intent("android.intent.action.MAIN");
sendIntent.setComponent(new ComponentName("com.whatsapp", "com.whatsapp.Conversation"));
sendIntent.putExtra("jid", PhoneNumberUtils.stripSeparators(smsNumber) + "#s.whatsapp.net");//phone number without "+" prefix
startActivity(sendIntent);
} else {
Uri uri = Uri.parse("market://details?id=com.whatsapp");
Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
Toast.makeText(this, "WhatsApp not Installed",
Toast.LENGTH_SHORT).show();
startActivity(goToMarket);
}
}
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;
}
Check out my answer : https://stackoverflow.com/a/40285262/5879376
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.
Whatsapp have its own API
Intent sendIntent = new Intent("android.intent.action.MAIN");
sendIntent.setAction(Intent.ACTION_VIEW);
sendIntent.setPackage("com.whatsapp");
String url = "https://api.whatsapp.com/send?phone=" + "Phone with international format" + "&text=" + "your message";
sendIntent.setData(Uri.parse(url));
if(sendIntent.resolveActivity(context.getPackageManager()) != null){
startActivity(sendIntent);
}
Code updated check added for Activity is available or not.
See this documentation
Here am trying to send a text message in WhatsApp with another application.
Assume that we have a button, on button click ur calling below method.
sendTextMsgOnWhatsApp("+91 9876543210", "Hello, this my test message");
public void sendTextMsgOnWhatsApp(String sContactNo, String sMessage) {
String toNumber = sContactNo; // contains spaces, i.e., example +91 98765 43210
toNumber = toNumber.replace("+", "").replace(" ", "");
/*this method contactIdByPhoneNumber() will get unique id for given contact,
if this return's null then it means that you don't have any contact save with this mobile no.*/
String sContactId = contactIdByPhoneNumber(toNumber);
if (sContactId != null && sContactId.length() > 0) {
/*
* Once We get the contact id, we check whether contact has a registered with WhatsApp or not.
* this hasWhatsApp(hasWhatsApp) method will return null,
* if contact doesn't associate with whatsApp services.
* */
String sWhatsAppNo = hasWhatsApp(sContactId);
if (sWhatsAppNo != null && sWhatsAppNo.length() > 0) {
Intent sendIntent = new Intent("android.intent.action.MAIN");
sendIntent.putExtra("jid", toNumber + "#s.whatsapp.net");
sendIntent.putExtra(Intent.EXTRA_TEXT, sMessage);
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.setPackage("com.whatsapp");
sendIntent.setType("text/plain");
startActivity(sendIntent);
} else {
// this contact does not exist in any WhatsApp application
Toast.makeText(this, "Contact not found in WhatsApp !!", Toast.LENGTH_SHORT).show();
}
} else {
// this contact does not exist in your contact
Toast.makeText(this, "create contact for " + toNumber, Toast.LENGTH_SHORT).show();
}
}
private String contactIdByPhoneNumber(String phoneNumber) {
String contactId = null;
if (phoneNumber != null && phoneNumber.length() > 0) {
ContentResolver contentResolver = getContentResolver();
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
String[] projection = new String[]{ContactsContract.PhoneLookup._ID};
Cursor cursor = contentResolver.query(uri, projection, null, null, null);
if (cursor != null) {
while (cursor.moveToNext()) {
contactId = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.PhoneLookup._ID));
}
cursor.close();
}
}
return contactId;
}
public String hasWhatsApp(String contactID) {
String rowContactId = null;
boolean hasWhatsApp;
String[] projection = new String[]{ContactsContract.RawContacts._ID};
String selection = ContactsContract.RawContacts.CONTACT_ID + " = ? AND " + ContactsContract.RawContacts.ACCOUNT_TYPE + " = ?";
String[] selectionArgs = new String[]{contactID, "com.whatsapp"};
Cursor cursor = getContentResolver().query(ContactsContract.RawContacts.CONTENT_URI, projection, selection, selectionArgs, null);
if (cursor != null) {
hasWhatsApp = cursor.moveToNext();
if (hasWhatsApp) {
rowContactId = cursor.getString(0);
}
cursor.close();
}
return rowContactId;
}
Add this below permission in AndroidManifest.xml file
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.INTERNET" />
This will first search for the specified contact and then open a chat window.
And if WhatsApp is not installed then try-catch block handle this.
String digits = "\\d+";
String mob_num = "987654321";
if (mob_num.matches(digits))
{
try {
//linking for whatsapp
Uri uri = Uri.parse("whatsapp://send?phone=+91" + mob_num);
Intent i = new Intent(Intent.ACTION_VIEW, uri);
startActivity(i);
}
catch (ActivityNotFoundException e){
e.printStackTrace();
//if you're in anonymous class pass context like "YourActivity.this"
Toast.makeText(this, "WhatsApp not installed.", Toast.LENGTH_SHORT).show();
}
}
This is the shortest way
String mPhoneNumber = "+972505555555";
mPhoneNumber = mPhoneNumber.replaceAll("+", "").replaceAll(" ", "").replaceAll("-","");
String mMessage = "Hello world";
String mSendToWhatsApp = "https://wa.me/" + mPhoneNumber + "?text="+mMessage;
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse(
mSendToWhatsApp
)));
See also the documentation of WhatsApp
try {
String text = "Hello, Admin sir";// Replace with your message.
String toNumber = "xxxxxxxxxxxx"; // Replace with mobile phone number without +Sign or leading zeros, but with country code
//Suppose your country is India and your phone number is “xxxxxxxxxx”, then you need to send “91xxxxxxxxxx”.
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("http://api.whatsapp.com/send?phone=" + toNumber + "&text=" + text));
context.startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=com.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.
you can also select WhatsApp business vs WhatsApp
String url = "https://api.whatsapp.com/send?phone=" + phoneNumber + "&text=" +
URLEncoder.encode(messageText, "UTF-8");
if(useWhatsAppBusiness){
intent.setPackage("com.whatsapp.w4b");
} else {
intent.setPackage("com.whatsapp");
}
URLEncoder.encode(messageText, "UTF-8");
intent.setData(Uri.parse(url));
if (intent.resolveActivity(packageManager) != null) {
startActivity(intent);
} else {
Toast.makeText(this, "WhatsApp application not found", Toast.LENGTH_SHORT).show();
}
try this, worked for me ! . Just use intent
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(whatsappUrl()));
startActivity(intent);
Build whatsapp url. add country code in whatsapp phone number https://countrycode.org/
public static String whatsappUrl(){
final String BASE_URL = "https://api.whatsapp.com/";
final String WHATSAPP_PHONE_NUMBER = "628123232323"; //'62' is country code for Indonesia
final String PARAM_PHONE_NUMBER = "phone";
final String PARAM_TEXT = "text";
final String TEXT_VALUE = "Hello, How are you ?";
String newUrl = BASE_URL + "send";
Uri builtUri = Uri.parse(newUrl).buildUpon()
.appendQueryParameter(PARAM_PHONE_NUMBER, WHATSAPP_PHONE_NUMBER)
.appendQueryParameter(PARAM_TEXT, TEXT_VALUE)
.build();
return buildUrl(builtUri).toString();
}
public static URL buildUrl(Uri myUri){
URL finalUrl = null;
try {
finalUrl = new URL(myUri.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
}
return finalUrl;
}
Send a text to specific contact programmatically (Whatsapp)
try {
val i = Intent(Intent.ACTION_VIEW)
val url = "https://api.whatsapp.com/send?phone=91XXXXXXXXXX&text=yourmessage"
i.setPackage("com.whatsapp")
i.data = Uri.parse(url)
startActivity(i)
} catch (e: Exception) {
e.printStackTrace()
val uri = Uri.parse("market://details?id=com.whatsapp")
val goToMarket = Intent(Intent.ACTION_VIEW, uri)
startActivity(goToMarket)
}
private void openWhatsApp() {
//without '+'
try {
Intent sendIntent = new Intent("android.intent.action.MAIN");
//sendIntent.setComponent(new ComponentName("com.whatsapp", "com.whatsapp.Conversation"));
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.setType("text/plain");
sendIntent.putExtra("jid",whatsappId);
sendIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
sendIntent.setPackage("com.whatsapp");
startActivity(sendIntent);
} catch(Exception e) {
Toast.makeText(this, "Error/n" + e.toString(), Toast.LENGTH_SHORT).show();
Log.e("Error",e+"") ; }
}
In Python, you can do it the same way we do it with mobile application
web.open('https://web.whatsapp.com/send?phone='+phone_no+'&text='+message)
This will prepopulate the text for given mobile number(Enter the phone_no as CountryCode and the number eg +918888888888)
Then using pyautogui you can press enter onto whatsapp.web
Working code :
def sendwhatmsg(phone_no, message, time_hour, time_min):
'''Sends whatsapp message to a particulal number at given time'''
if time_hour == 0:
time_hour = 24
callsec = (time_hour*3600)+(time_min*60)
curr = time.localtime()
currhr = curr.tm_hour
currmin = curr.tm_min
currsec = curr.tm_sec
currtotsec = (currhr*3600)+(currmin*60)+(currsec)
lefttm = callsec-currtotsec
if lefttm <= 0:
lefttm = 86400+lefttm
if lefttm < 60:
raise Exception("Call time must be greater than one minute")
else:
sleeptm = lefttm-60
time.sleep(sleeptm)
web.open('https://web.whatsapp.com/send?phone='+phone_no+'&text='+message)
time.sleep(60)
pg.press('enter')
I've taken this from this repository - Github repo
This code is implemented with Kotlin.
I have 2 versions:
1) For known contacts
private fun openWhatsApp(dato: WhatsApp) {
val isAppInstalled = appInstalledOrNot("com.whatsapp")
if (isAppInstalled) {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse("https://api.whatsapp.com/send?phone=${dato.whatsapp}"))
startActivity(intent)
} else {
// WhatsApp not installed show toast or dialog
}
}
private fun appInstalledOrNot(uri: String): Boolean {
val pm = requireActivity().packageManager
return try {
pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES)
true
} catch (e: PackageManager.NameNotFoundException) {
false
}
}
In the case of being an unknown contact WhatsApp shows the following message
2) For unknown contacts
private fun openWhatsApp(dato: WhatsApp) {
val isAppInstalled = appInstalledOrNot("com.whatsapp")
if (isAppInstalled) {
val sendIntent = Intent("android.intent.action.MAIN")
sendIntent.setType("text/plain")
sendIntent.setComponent(ComponentName("com.whatsapp", "com.whatsapp.Conversation"))
sendIntent.putExtra("jid", PhoneNumberUtils.stripSeparators(dato.whatsapp) + "#s.whatsapp.net")
startActivity(sendIntent)
} else {
// WhatsApp not installed show toast or dialog
}
}
private fun appInstalledOrNot(uri: String): Boolean {
val pm = requireActivity().packageManager
return try {
pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES)
true
} catch (e: PackageManager.NameNotFoundException) {
false
}
}
Use this function. Don't forget to save the WhatsApp Number on your mobile before sending trigger the function.
private void openWhatsApp() {
Uri uri = Uri.parse("smsto:"+ "12345");
Intent i = new Intent(Intent.ACTION_SENDTO,uri);
i.setPackage("com.whatsapp");
startActivity(i);
}
Update 2020
String number="+91 7*********";
String url="https://api.whatsapp.com/send?phone="+number + "&text=" + "Your text here";
Intent i=new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
Here is a way how to send message in WhatsApp in KOTLIN
private fun sendMessage(phone: String, message: String) {
val pm = requireActivity().packageManager
val i = Intent(Intent.ACTION_VIEW)
try {
val url = "https://api.whatsapp.com/send?phone=$phone&text=" + URLEncoder.encode(
message,
"UTF-8"
)
i.setPackage("com.whatsapp")
i.data = Uri.parse(url)
if (i.resolveActivity(pm) != null) {
context?.startActivity(i)
}
} catch (e: PackageManager.NameNotFoundException) {
Toast.makeText(requireContext(), "WhatsApp not Installed", Toast.LENGTH_SHORT).show()
}
}
The following will open up the Whatsapp conversation (with a contact) page and prefill it with the text provided. Note: This is not going to automatically send the text off to the Whatsapp servers. It will only open the conversation page. The user needs to explicitly press the "Send" button to actually have the text sent to the servers.
String phoneId = "+1415xxxyyyy"; // the (Whatsapp) phone number of contact
String text = "text to send";
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.setType("text/plain");
sendIntent.putExtra(Intent.EXTRA_TEXT, text);
sendIntent.putExtra("jid", phoneId);
sendIntent.setPackage("com.whatsapp");
startActivity(sendIntent);
Check this answer. Here your number start with "91**********".
Intent sendIntent = new Intent("android.intent.action.MAIN");
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.setType("text/plain");
sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send."); sendIntent.putExtra("jid",PhoneNumberUtils.stripSeparators("91**********") + "#s.whatsapp.net");
sendIntent.setPackage("com.whatsapp");
startActivity(sendIntent);
This will first search for the specified contact and then open a chat window.
Note: phone_number and str are variables.
Uri mUri = Uri.parse("https://api.whatsapp.com/send?
phone=" + phone_no + "&text=" + str);
Intent mIntent = new Intent("android.intent.action.VIEW", mUri);
mIntent.setPackage("com.whatsapp");
startActivity(mIntent);
Bitmap bmp = null;
bmp = ((BitmapDrawable) tmpimg.getDrawable()).getBitmap();
Uri bmpUri = null;
try {
File file = new File(getBaseContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES), "share_image_" + System.currentTimeMillis() + ".jpg");
FileOutputStream out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
bmpUri = Uri.fromFile(file);
} catch (IOException e) {
e.printStackTrace();
}
String toNumber = "+919999999999";
toNumber = toNumber.replace("+", "").replace(" ", "");
Intent shareIntent =new Intent("android.intent.action.MAIN");
shareIntent.setAction(Intent.ACTION_SEND);
String ExtraText;
ExtraText = "Share Text";
shareIntent.putExtra(Intent.EXTRA_TEXT, ExtraText);
shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
shareIntent.setType("image/jpg");
shareIntent.setPackage("com.whatsapp");
shareIntent.putExtra("jid", toNumber + "#s.whatsapp.net");
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
try {
startActivity(shareIntent);
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(getBaseContext(), "Sharing tools have not been installed.", Toast.LENGTH_SHORT).show();
}
}
private void sendToContactUs() {
String phoneNo="+918000874386";
Intent sendIntent = new Intent("android.intent.action.MAIN");
sendIntent.setAction(Intent.ACTION_VIEW);
sendIntent.setPackage("com.whatsapp");
String url = "https://api.whatsapp.com/send?phone=" + phoneNo + "&text=" + "Unique Code - "+CommonUtils.getMacAddress();
sendIntent.setDataAndType(Uri.parse(url),"text/plain");
if(sendIntent.resolveActivity(getPackageManager()) != null){
startActivity(sendIntent);
}else{
Toast.makeText(getApplicationContext(),"Please Install Whatsapp Massnger App in your Devices",Toast.LENGTH_LONG).show();
}
}
public void shareWhatsup(String text) {
String smsNumber = "91+" + "9879098469"; // E164 format without '+' sign
Intent intent = new Intent(Intent.ACTION_VIEW);
try {
String url = "https://api.whatsapp.com/send?phone=" + smsNumber + "&text=" + URLEncoder.encode(text, "UTF-8");
intent.setPackage("com.whatsapp");
intent.setData(Uri.parse(url));
} catch (Exception e) {
e.printStackTrace();
}
// intent.setAction(Intent.ACTION_SEND);
// intent.setType("image/jpeg");
// intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageUriArray);
startActivity(intent);
}
Instead of biasing to share the content to whats app.
Following code is a generic code that will give a simple solution using "ShareCompact" that android opens the list of apps that supports the sharing the content.
Here I am sharing the data of mime-type text/plain.
String mimeType = "text/plain"
String Message = "Hi How are you doing?"
ShareCompact.IntentBuilder
.from(this)
.setType(mimeType)
.setText(Message)
.startChooser()
Whatsapp and most other apps that integrate into the Android core components (like Contacts) use a mime-type based intent to launch a certain Activity within the application. Whatsapp uses 3 separate mimetypes - text messages (vnd.android.cursor.item/vnd.com.whatsapp.profile), voip calls (vnd.android.cursor.item/vnd.com.whatsapp.voip.call) and video calls(vnd.android.cursor.item/vnd.com.whatsapp.video.call). For each of these mimetypes, a separate activity is mapped inside the Manifest of the application. For ex: the mimetype (...whatsapp.profile) maps to an Activity (com.whatsapp.Conversation). You can see these in detail if you dump out all the Data rows that maps to any Whatsapp Raw_Contact in your Contacts database.
This is also how the Android Contacts app shows 3 separate rows of user action inside a "Whatsapp contact", and clicking either of these rows launches a separate function inside Whatsapp.
To launch a Conversation (chat) Activity for a certain contact in Whatsapp, you need to fire an intent containing MIME_TYPE and DATA_URL. The mimetype points to the mimetype corresponding to your action as defined inside Whatsapp's Raw Contact in Contacts database. The DATA_URL is the URI of the Raw_Contact in the Android contacts database.
String whatsAppMimeType = Uri.parse("vnd.android.cursor.item").buildUpon()
.appendEncodedPath("vnd.com.whatsapp.profile").build().toString();
Uri uri = ContactsContract.RawContacts.CONTENT_URI.buildUpon()
.appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_TYPE, "com.whatsapp")
.appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_NAME, "WhatsApp")
.build();
Cursor cursor = getContentResolver().query(uri, null, null, null);
if (cursor==null || cursor.getCount()==0) continue;
cursor.moveToNext();
int rawContactId = cursor.getInt(cursor.getColumnIndex(ContactsContract.RawContacts._ID));
cursor.close();
// now search for the Data row entry that matches the mimetype and also points to this RawContact
Cursor dataCursor = getContentResolver().query(ContactsContract.Data.CONTENT_URI,
null,
ContactsContract.Data.MIMETYPE + "=? AND " + ContactsContract.Data.RAW_CONTACT_ID + "=?",
new String[]{whatsAppMimeType, String.valueOf(rawContactId)}, null);
if (dataCursor==null || dataCursor.getCount()==0) continue;
dataCursor.moveToNext();
int dataRowId = dataCursor.getInt(dataCursor.getColumnIndex(ContactsContract.Data._ID));
Uri userRowUri = ContactsContract.Data.CONTENT_URI.buildUpon()
.appendPath(String.valueOf(dataRowId)).build();
// launch the whatsapp user chat activity
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(userRowUri, whatsAppMimeType);
startActivity(intent);
dataCursor.close();
This is the same way that all Contacts app use to launch a chat Activity for a Whatsapp contact. Inside this Activity, the application (Whatsapp) reads in the .getData() to get the DATA_URI which was passed to this Activity. The Android Contacts app uses a standard mechanism to use the URI of the Raw Contact in Whatsapp. Unfortunately, I am not aware of a way by which the .Conversation ativity in Whatsapp reads in any text / data information from the caller of the intent. This basically means that its possible (using a very standard technique) to launch a certain "user action" inside Whatsapp. Or for that matter, any similar app.
I want to open native application to send sms but there should be already phone number. I found ACTION_SEND but when I'm calling my function it's return error that:
04-26 11:59:15.991: ERROR/AndroidRuntime(20198): android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.SENDTO (has extras) }
My code presented here:
private void smsSend(String number) {
Intent intent = new Intent(Intent.ACTION_SENDTO, null);
intent.putExtra(Intent.EXTRA_PHONE_NUMBER, number);
startActivity(intent);
}
I know that's is simple but I don't know why it does not work and I can not find any helfull information.
Thanks for any advice.
Why, this should work fine. http://developer.android.com/reference/android/content/Intent.html#ACTION_SENDTO
Check out my code:
Uri uri = Uri.parse("smsto:0800000123");
Intent it = new Intent(Intent.ACTION_SENDTO, uri);
it.putExtra("sms_body", "The SMS text");
startActivity(it);
Thanks for the info !
Here is my solution using the previous info:
if (url.indexOf("tel:") > -1) {
startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse(url)));
return true;
}
else if (url.indexOf("sms:") > -1){
startActivity(new Intent(Intent.ACTION_SENDTO, Uri.parse(url)));
return true;
}
Best regards.
I think you should use the following code:
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
//use to fill the sms body
StringBuilder uri = new StringBuilder("sms:" + mobilenumber);
sendIntent.putExtra("sms_body", "");
sendIntent.setType("vnd.android-dir/mms-sms");
sendIntent.setData("");
startActivity(sendIntent);
I think this may help you.
On my side, the intent without uri parameter work for all devices,
except for Pixel Phone where I need to use it, so I check the 2 ways:
Intent smsIntent = new Intent(Intent.ACTION_VIEW);
smsIntent.setType("vnd.android-dir/mms-sms");
final Context context = activity.getApplicationContext();
final String phoneNumber = "1234567890";
final String msg = "Hello!";
smsIntent.putExtra("address", phoneNumber);
smsIntent.putExtra("sms_body", msg);
smsIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP |
Intent.FLAG_ACTIVITY_CLEAR_TOP);
final PackageManager manager = context.getPackageManager();
List<ResolveInfo> infos = manager.queryIntentActivities(smsIntent, 0);
if (infos.size() <1) {
//No Application can handle your intent
//try in a another way ...
Uri uri = Uri.parse("smsto:"+phoneNumber);
smsIntent = new Intent(Intent.ACTION_SENDTO, uri);
smsIntent.putExtra("sms_body", msg);
infos = manager.queryIntentActivities(smsIntent, 0);
}
if (infos.size() <1) {
//No Application can handle your intent
Log.e("SendMessage","No Application can handle your SMS intent");
}
In kotlin following code works with number and custom message
val defaultSmsPackageName = Telephony.Sms.getDefaultSmsPackage(activity)
val sendIntent = Intent(Intent.ACTION_SEND)
sendIntent.type = "text/plain"
sendIntent.putExtra("address", "sms:"+contactNumber)
sendIntent.putExtra(Intent.EXTRA_TEXT, getString(R.string.share_msg_body))
Timber.e("defaultSmsPackageName: "+defaultSmsPackageName)
if (defaultSmsPackageName != null){ //Can be null in case that there is no default, then the user would be able to choose any app that support this intent.
sendIntent.setPackage(defaultSmsPackageName)
activity!!.startActivity(sendIntent)
}
I have a question about an intent...
I try to launch the sms app...
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setType("vnd.android-dir/mms-sms");
int flags = Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP |
Intent.FLAG_ACTIVITY_CLEAR_TOP;
intent.setFlags(flags);
intent.setData(Uri.parse("content://sms/inbox"));
context.startActivity(intent);
so, you can see that I put too much things in my intent, but that's because I don't know how I can do...
Thank's
To start launch the sms activity all you need is this:
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.setData(Uri.parse("sms:"));
You can add extras to populate your own message and such like this
sendIntent.putExtra("sms_body", x);
then just startActivity with the intent.
startActivity(sendIntent);
Intent smsIntent = new Intent(Intent.ACTION_VIEW);
smsIntent.setType("vnd.android-dir/mms-sms");
smsIntent.putExtra("address", "12125551212");
smsIntent.putExtra("sms_body","Body of Message");
startActivity(smsIntent);
If android version is Kitkat or above, users can change default sms application. This method will get default sms app and start default sms app.
private void sendSMS() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) // At least KitKat
{
String defaultSmsPackageName = Telephony.Sms.getDefaultSmsPackage(this); // Need to change the build to API 19
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.setType("text/plain");
sendIntent.putExtra(Intent.EXTRA_TEXT, "text");
if (defaultSmsPackageName != null)// Can be null in case that there is no default, then the user would be able to choose
// any app that support this intent.
{
sendIntent.setPackage(defaultSmsPackageName);
}
startActivity(sendIntent);
}
else // For early versions, do what worked for you before.
{
Intent smsIntent = new Intent(android.content.Intent.ACTION_VIEW);
smsIntent.setType("vnd.android-dir/mms-sms");
smsIntent.putExtra("address","phoneNumber");
smsIntent.putExtra("sms_body","message");
startActivity(smsIntent);
}
}
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.setType("vnd.android-dir/mms-sms");
startActivity(intent);
That's all you need.
If you want to launch SMS Composing activity from some of your other activity and you also have to pass a phone number and SMS text, then use this code:
Uri sms_uri = Uri.parse("smsto:+92xxxxxxxx");
Intent sms_intent = new Intent(Intent.ACTION_SENDTO, sms_uri);
sms_intent.putExtra("sms_body", "Good Morning ! how r U ?");
startActivity(sms_intent);
Note: here the sms_body and smsto: is keys for recognizing the text and phone no at SMS compose activity, so be careful here.
Here is the code that will open the SMS activity pre-populated with the phone number to
which the SMS has to be sent. This works fine on emulator as well as the device.
Intent smsIntent = new Intent(Intent.ACTION_SENDTO);
smsIntent.addCategory(Intent.CATEGORY_DEFAULT);
smsIntent.setType("vnd.android-dir/mms-sms");
smsIntent.setData(Uri.parse("sms:" + phoneNumber));
startActivity(smsIntent);
In kotlin this can be implemented easily as follows:
/**
* If android version is Kitkat or above, users can change default sms application.
* This method will get default sms app and start default sms app.
*/
private fun openSMS() {
val message = "message here"
val phone = "255754......." //255 Tanzania code.
val uri = Uri.parse("smsto:+$phone")
val intent = Intent(Intent.ACTION_SENDTO, uri)
with(intent) {
putExtra("address", "+$phone")
putExtra("sms_body", message)
}
when {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT -> {
//Getting the default sms app.
val defaultSmsPackageName = Telephony.Sms.getDefaultSmsPackage(context)
// Can be null in case that there is no default, then the user would be able to choose
// any app that support this intent.
if (defaultSmsPackageName != null) intent.setPackage(defaultSmsPackageName)
startActivity(intent)
}
else -> startActivity(intent)
}
}
This is modified answer of #mustafasevgi
Use
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.setClassName("com.android.mms", "com.android.mms.ui.ConversationList");
I use:
Intent sendIntent = new Intent(Intent.ACTION_MAIN);
sendIntent.putExtra("sms_body", "text");
sendIntent.setType("vnd.android-dir/mms-sms");
startActivity(sendIntent);
Intent eventIntentMessage =getPackageManager()
.getLaunchIntentForPackage(Telephony.Sms.getDefaultSmsPackage(getApplicationContext));
startActivity(eventIntentMessage);
try {
Intent smsIntent = new Intent(Intent.ACTION_VIEW);
smsIntent.setData(Uri.parse("smsto:" + Uri.encode(number)));
smsIntent.putExtra("address", number);
smsIntent.putExtra("sms_body", message);
PackageManager pm = activity.getPackageManager();
List<ResolveInfo> resInfo = pm.queryIntentActivities(smsIntent, 0);
for (int i = 0; i < resInfo.size(); i++) {
ResolveInfo ri = resInfo.get(i);
String packageName = ri.activityInfo.packageName;
if (packageName.contains("sms")) {
//Log.d("TAG", packageName + " : " + ri.activityInfo.name);
smsIntent.setComponent(new ComponentName(packageName, ri.activityInfo.name));
}
}
activity.startActivity(smsIntent);
} catch (Exception e) {
// Handle Error
}
Best way of doing this.
You can open default sms App and pass details as below :
Note : If u want to send to many numbers, separate each number with ";" inside string
String mblNumVar = "9876543210;9123456789";
Intent smsMsgAppVar = new Intent(Intent.ACTION_VIEW);
smsMsgAppVar.setData(Uri.parse("sms:" + mblNumVar));
smsMsgAppVar.putExtra("sms_body", "Hello Msg Tst Txt");
startActivity(smsMsgAppVar);
|Or| Use this function :
void openSmsMsgAppFnc(String mblNumVar, String smsMsgVar)
{
Intent smsMsgAppVar = new Intent(Intent.ACTION_VIEW);
smsMsgAppVar.setData(Uri.parse("sms:" + mblNumVar));
smsMsgAppVar.putExtra("sms_body", smsMsgVar);
startActivity(smsMsgAppVar);
}
Intent sendIntent = new Intent(Intent.ACTION_SEND);
//CHANGE YOUR MESSAGING ACTIVITY HERE IF REQUIRED
sendIntent.setClassName("com.android.mms", "com.android.mms.ui.ComposeMessageActivity");
sendIntent.putExtra("sms_body",msgbody);
sendIntent.putExtra("address",phonenumber);
//FOR MMS
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///sdcard/mms.png"));
sendIntent.setType("image/png");
startActivity(sendIntent);
The best code that works with Default SMS app is.
Uri SMS_URI = Uri.parse("smsto:+92324502****"); //Replace the phone number
Intent sms = new Intent(Intent.ACTION_VIEW,SMS_URI);
sms.putExtra("sms_body","This is test message"); //Replace the message witha a vairable
startActivity(sms);
Compose SMS :
Uri smsUri = Uri.parse("tel:" + to);
Intent intent = new Intent(Intent.ACTION_VIEW, smsUri);
intent.putExtra("address", to);
intent.putExtra("sms_body", message);
intent.setType("vnd.android-dir/mms-sms");
startActivity(intent);
The below code works on android 6.0.
It will open the search activity in the default messaging application with the conversations related to specific string provided.
Intent smsIntent = new Intent(Intent.ACTION_MAIN);
smsIntent.addCategory(Intent.CATEGORY_LAUNCHER);
smsIntent.setClassName("com.android.mms", "com.android.mms.ui.SearchActivity");
smsIntent.putExtra("intent_extra_data_key", "string_to_search_for");
startActivity(smsIntent);
You can start the search activity with an intent. This will open the search activity of the default messaging application.
Now, to show a list of specific conversations in the search activity, you can provide the search string as string extra with the key as
"intent_extra_data_key"
as is shown in the onCreate of this class
String searchStringParameter = getIntent().getStringExtra(SearchManager.QUERY);
if (searchStringParameter == null) {
searchStringParameter = getIntent().getStringExtra("intent_extra_data_key" /*SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA*/);
}
final String searchString = searchStringParameter != null ? searchStringParameter.trim() : searchStringParameter;
You can also pass the SENDER_ADDRESS of the sms as string extra, which will list out all the conversations with that specific sender address.
Check com.android.mms.ui.SearchActivity for more information
You can also check this answer
For Kotlin simply do that:
val messageIntent = Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:03xxxxxxxxx"))
messageIntent.putExtra("sms_body", "Enter your body here")
startActivity(messageIntent)
on emulator this work for me
Intent i = new Intent(Intent.ACTION_VIEW, Uri.fromParts("sms", number, null));
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("sms_body", remindingReason);
startActivity(i);
Sms Intent :
Intent intent = new Intent("android.intent.action.VIEW");
/** creates an sms uri */
Uri data = Uri.parse("sms:");
intent.setData(data);
Either you can use this ,both are working fine on android above 4.4
Intent smsIntent = new Intent(Intent.ACTION_VIEW);
smsIntent.setType("vnd.android-dir/mms-sms");
smsIntent.putExtra("address","9212107320");
smsIntent.putExtra("sms_body","Body of Message");
startActivity(smsIntent);
or
Intent smsIntent = new Intent(Intent.ACTION_VIEW);
smsIntent.putExtra("sms_body","Body of Message");
smsIntent.setData(Uri.parse("sms:9212107320"));
startActivity(smsIntent);
You can use the following code snippet to achieve your goal:
Intent smsIntent = new Intent(Intent.ACTION_SENDTO);
smsIntent.setData(Uri.parse("smsto:"+model.getPhoneNo().trim()));
smsIntent.addCategory(Intent.CATEGORY_DEFAULT);
smsIntent.putExtra("sms_body","Hello this is dummy text");
startActivity(smsIntent);
If you don't want any text then remove the sms_body key.
Intent smsIntent = new Intent(Intent.ACTION_SENDTO);
smsIntent.setData(Uri.parse("smsto:"+shopkepperDataModel.getPhoneNo().trim()));
smsIntent.addCategory(Intent.CATEGORY_DEFAULT);
startActivity(smsIntent);
Works up to Android 11. (Supports all supported SDKs)
btnMessageTo.setOnClickListener {
val phoneNumber = "+8801234567890"
val intent = Intent("android.intent.action.SENDTO")
intent.data =
Uri.parse("smsto:" + Uri.encode(phoneNumber ))
startActivity(intent)
}