how can i pass my string to the email intent service? - java

gen_btn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
String to = text.getText().toString().trim();
String subject = text2.getText().toString().trim();
String content = text3.getText().toString().trim();
StringBuffer buffer = new StringBuffer();
Intent email = new Intent(Intent.ACTION_SEND);
email.putExtra(Intent.EXTRA_SUBJECT, subject);
email.putExtra(Intent.EXTRA_EMAIL,to );
email.putExtra(Intent.EXTRA_TEXT, content);
email.setType("message/rfc822");
startActivity(email);
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
try {
BitMatrix bitMatrix = multiFormatWriter.encode(
email.getAction(), BarcodeFormat.QR_CODE, 250, 250
);
BarcodeEncoder barcodeEncoder=new BarcodeEncoder();
Bitmap bitmap = barcodeEncoder.createBitmap(bitMatrix);
image.setImageBitmap(bitmap);
}
catch (WriterException e){
e.printStackTrace();
}
}
});
i want to generate an email, as you can see, i got three edit text(to, subject, content) and i already insert the email intent, when i generate it catch all the string and i send the string through email app, but the problem is, all of my string does not get to their respective email format. where did i do wrong? sorry if you cant understand what i am asking all i can do is to show my code. i am new to android java so please help.

If I understood correctly you are trying to send email through the email app. This might be helpful.
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("plain/text");
intent.putExtra(Intent.EXTRA_EMAIL, to);
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
intent.putExtra(Intent.EXTRA_TEXT, content);
startActivity(Intent.createChooser(intent, ""));

Related

I cant run the email intent code on my phone

enter image description here
the email intent code is completely run in the android mobile model provided by android studio but when I run the code in my personal phone its not work…
please answer ??
Don't forget to set the type of intent so it will trigger email clients
Intent email = new Intent(Intent.ACTION_SEND);
email.putExtra(Intent.EXTRA_EMAIL, new String[]{ to});
email.putExtra(Intent.EXTRA_SUBJECT, subject);
email.putExtra(Intent.EXTRA_TEXT, message);
//need this to prompts email client only
email.setType("message/rfc822");
startActivity(Intent.createChooser(email, "Choose an Email client :"));
Kotlin code,
val selectorIntent = Intent(Intent.ACTION_SENDTO)
selectorIntent.data = Uri.parse("mailto:")
val emailIntent = Intent(Intent.ACTION_SEND)
emailIntent.putExtra(Intent.EXTRA_EMAIL, arrayOf<String>("mail id"))
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject")
emailIntent.selector = selectorIntent
startActivity(Intent.createChooser(emailIntent, "Send email..."))
Java code,
Intent selectorIntent = new Intent(Intent.ACTION_SENDTO);
selectorIntent.setData(Uri.parse("mailto:"));
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{"mail id"});
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
emailIntent.setSelector(selectorIntent);
startActivity(Intent.createChooser(emailIntent, "Send email..."));
Intent intEmail = new Intent(Intent.ACTION_SENDTO);
intEmail.setType("plain/text");
intEmail.setData(Uri.parse("mailto:"));
intEmail.putExtra(Intent.EXTRA_EMAIL, new String[]{"receiver_email_address"});
if (intEmail.resolveActivity(getPackageManager()) != null){
startActivity(intEmail);
}
I tested the code of mayar hassan, it worked fine on my side. [on Samsung Android 8.1]
The code:
public class TestSentMail extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_sent_mail);
Button button = findViewById(R.id.submitButton);
button.setOnClickListener(view -> {
submitOrder();
});
}
private void submitOrder() {
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setData(Uri.parse("mailto:"));
intent.putExtra(Intent.EXTRA_SUBJECT, "coffe order for tancolo");
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}
}
The screenshot:
How to fix your problem
In general, I think we should do these as below.
Check the log in the Logcat panel in Android Studio, maybe there are exceptions.
Added your debug code where you want to add.
val i = Intent(Intent.ACTION_SEND)
i.type = "message/rfc822"
i.putExtra(Intent.EXTRA_EMAIL, arrayOf<String>("sumsolutions.net#gmail.com"))
i.putExtra(Intent.EXTRA_SUBJECT, "Feedback")
i.putExtra(Intent.EXTRA_TEXT, "Text here...")
try {
startActivity(Intent.createChooser(i, "Send mail..."))
} catch (ex: ActivityNotFoundException) {
Toast.makeText(this, "There are no email clients installed.", Toast.LENGTH_SHORT)
.show()
}

How to attach image to email on Android emailIntent

To send the email the method for the button is;
public void buttonSendEmailClicked(View view) {
File file = saveFileToShare();
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.setType("application/image");
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{});
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,"Check Out MyPic");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Taken With Android!");
emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
startActivityForResult(Intent.createChooser(emailIntent, "Send mail..."), interstitial_request);
}
The saveFileToShare element is this;
public File saveFileToShare() {
try
{
File fileImage = new File(Environment.getExternalStorageDirectory() + "/DCIM/Camera/attachment.png");
if(!fileImage.exists())
{
fileImage.delete();
}
editorImage.setDrawingCacheEnabled(true);
Bitmap bitmap = editorImage.getDrawingCache();
fileImage.createNewFile();
FileOutputStream ostream = new FileOutputStream(fileImage);
bitmap.compress(CompressFormat.PNG, 100, ostream);
ostream.close();
editorImage.invalidate();
editorImage.setDrawingCacheEnabled(false);
return fileImage;
}
catch (Exception e)
{
System.out.print(e);
e.printStackTrace();
return null;
}
}
Saving the image works fine, the save code is;
public void buttonSaveImageClicked(View view) throws IOException {
editorImage.setDrawingCacheEnabled(true);
Bitmap bitmap = editorImage.getDrawingCache();
SaveLayoutToFile saveImage = new SaveLayoutToFile(this, bitmap, editorImage);
String filePath = Environment.getExternalStorageDirectory() + "/DCIM/Camera/wonkydog";
saveImage.execute(filePath);
}
I need to set the email code to grab the image and attach to email.
At the moment when I press the email button it just returns to the title screen without doing anything else.
If I comment out this line
emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
Then it opens the mail send dialogue, but without attachment of course...
I found the answer, rather than using the emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
I replaced it with;
emailIntent.putExtra(Intent.EXTRA_STREAM, FileProvider.getUriForFile(EditorActivity.this, "com.myapp.myappname.provider", file));
It now works correctly!

How to open gmail in android

I just wanted to open the Gmail app through my app and wanted to set email, subject and message from my application.
I have tried GmailService but it is not supporting bcc or cc emails.
Link: https://github.com/yesidlazaro/GmailBackground
BackgroundMail.newBuilder(this)
.withUsername("username#gmail.com")
.withPassword("password12345")
.withMailto("toemail#gmail.com")
.withType(BackgroundMail.TYPE_PLAIN)
.withSubject("this is the subject")
.withBody("this is the body")
.withOnSuccessCallback(new BackgroundMail.OnSuccessCallback() {
#Override
public void onSuccess() {
//do some magic
}
}).withOnFailCallback(new BackgroundMail.OnFailCallback() {
#Override
public void onFail() {
//do some magic
}
}).send();
I would like to use bcc and cc functionality along with the attachment, subject, and message.
// For Email by Any app
Intent email= new Intent(Intent.ACTION_SENDTO);
email.setData(Uri.parse("mailto:your.email#gmail.com"));
email.putExtra(Intent.EXTRA_SUBJECT, "Subject");
email.putExtra(Intent.EXTRA_TEXT, "My Email message");
startActivity(email);
open gmail via Intent
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("abc#gmail.com"));
intent.setClassName("com.google.android.gm", "com.google.android.gm.ComposeActivityGmail");
intent.putExtra(Intent.EXTRA_CC, new String[]{"xyz#gmail.com"});
intent.putExtra(Intent.EXTRA_BCC, new String[]{"pqr#gmail.com"});
intent.putExtra(Intent.EXTRA_SUBJECT, "your subject goes here...");
intent.putExtra(Intent.EXTRA_TEXT, "Your message content goes here...");
startActivity(intent);
just pass EXTRA_CC & EXTRA_BCC in intent argument
Edit
Below answer will work on android 11
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setData(Uri.parse("mailto:"));
intent.putExtra(Intent.EXTRA_EMAIL, new String[]{"abc#gmail.com"});
intent.putExtra(Intent.EXTRA_SUBJECT, "Your subject here...");
intent.putExtra(Intent.EXTRA_TEXT,"Your message here...");
startActivity(intent);
Edit 2
val selectorIntent = Intent(Intent.ACTION_SENDTO)
selectorIntent.data = Uri.parse("mailto:")
val emailIntent = Intent(Intent.ACTION_SEND)
emailIntent.putExtra(Intent.EXTRA_EMAIL, arrayOf("recipient#mail.com"))
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject here...")
emailIntent.putExtra(Intent.EXTRA_TEXT, "Email Body...")
emailIntent.selector = selectorIntent
activity!!.startActivity(Intent.createChooser(emailIntent, "Send email..."))
// This is for Gmail App
Intent email= new Intent(Intent.ACTION_VIEW);
email.setType("message/rfc822")
.setData(Uri.parse("mailto:your.email#gmail.com"))
.putExtra(Intent.EXTRA_EMAIL, "your.email#gmail.com")
.putExtra(Intent.EXTRA_SUBJECT, "Subject")
.putExtra(Intent.EXTRA_TEXT, "My Email message")
.setPackage("com.google.android.gm");
startActivity(email);
I m using this to launch gmail app.
val intent: Intent? = activity.packageManager.getLaunchIntentForPackage("com.google.android.gm")
if (intent != null) {
startActivity(intent)
}
else{
showToast("Sorry...You don't have gmail app")
}
//This is open with gmail
Intent i = new Intent(Intent.ACTION_SENDTO);
i.setType("text/plain");
i.setData(Uri.parse("mailto:"));
i.putExtra(Intent.EXTRA_EMAIL , new String[]{"recipient#gmail.com"});
i.putExtra(Intent.EXTRA_SUBJECT, "Mail Subject");
i.putExtra(Intent.EXTRA_TEXT , "massage");
i.setPackage("com.google.android.gm");
try {
startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(AnotherActivity.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
I am using this
Intent mailClient = new Intent(Intent.ACTION_VIEW);
mailClient.setClassName("com.google.android.gm", "com.google.android.gm.ConversationListActivity");
startActivity(mailClient);
you can also try this
final Intent intent = new Intent(Intent.ACTION_VIEW)
.setType("plain/text")
.setData(Uri.parse("test#gmail.com"))
.setClassName("com.google.android.gm", "com.google.android.gm.ComposeActivityGmail")
.putExtra(Intent.EXTRA_EMAIL, new String[]{"test#gmail.com"})
.putExtra(Intent.EXTRA_SUBJECT, "test")
.putExtra(Intent.EXTRA_TEXT, "hello. this is a message sent from my demo app :-)");
startActivity(intent);
use for plenty of emails:
intent.putExtra(Intent.EXTRA_EMAIL, new String[] { "test#gmail.com" });
for single emails:
intent.setData(Uri.parse("test#gmail.com"));

Share in Navigation bar all worked perfect but in Whatsapp it's only display link not text

Share in Navigation bar all worked perfect but in WhatsApp it's only display link not text.
All other apps worked perfect telegram,mail etc... But in WhatsApp it's only display link not upper text.
try {
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
final String appPackageName = getApplicationContext().getPackageName();
String strAppLink = "https://play.google.com/store/apps/details?id=" + appPackageName;
shareIntent.setType("text/plain");
String shareBody = strAppLink;
String shareSub = "Hey Download this App Called\n Appname ........\nAt least One Time Try This\n";
shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, shareSub);
shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(shareIntent, "Share using"));
}
catch (ActivityNotFoundException e)
{
}
Try this
In java:
try {
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
final String appPackageName = getApplicationContext().getPackageName();
String strAppLink = "https://play.google.com/store/apps/details?id=" + appPackageName;
shareIntent.setType("text/plain");
String shareBody = strAppLink;
String shareSub = "Hey Download this App Called\n Appname ........\nAt least One Time Try This\n";
String data = shareSub + shareBody
// shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, shareSub);
shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, data);
startActivity(Intent.createChooser(shareIntent, "Share using"));
} catch (ActivityNotFoundException e) {
}
In kotlin:
try {
val shareIntent = Intent(android.content.Intent.ACTION_SEND)
val appPackageName = applicationContext.packageName
val strAppLink = "https://play.google.com/store/apps/details?id=$appPackageName"
shareIntent.type = "text/plain"
val shareSub = "Hey Download this App Called\n Appname ........\nAt least One Time Try This\n"
val data = shareSub + strAppLink
//shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, shareSub)
shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, data)
startActivity(Intent.createChooser(shareIntent, "Share using"))
} catch (e: ActivityNotFoundException) {
}
There is only one change to make is comment the line which sets the subject. Merge the subject text with text and set that merged text in android.content.Intent.EXTRA_TEXT.
It works.

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

I am developing an android app and I need to send a message to specific contact from WhatsApp.
I tried this code:
Uri mUri = Uri.parse("smsto:+999999999");
Intent mIntent = new Intent(Intent.ACTION_SENDTO, mUri);
mIntent.setPackage("com.whatsapp");
mIntent.putExtra("sms_body", "The text goes here");
mIntent.putExtra("chat",true);
startActivity(mIntent);
The problem is that the parameter "sms_body" is not received on WhatsApp, though the contact is selected.
There is a way. Make sure that the contact you are providing must be passed as a string in intent without the prefix "+". Country code should be appended as a prefix to the phone number .
e.g.: '+918547264285' should be passed as '918547264285' . Here '91' in beginning is country code .
Note :Replace the 'YOUR_PHONE_NUMBER' with contact to which you want to send the message.
Here is the snippet :
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");
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.
This new method, send message to a specific contact via whatsapp in Android. For more information look here
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_VIEW);
String url = "https://api.whatsapp.com/send?phone=" + number + "&text=" + path;
sendIntent.setData(Uri.parse(url));
activity.startActivity(sendIntent);here
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!
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. I have published this in my android app, so if you want to see it live try my app Bill Book
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!
We can share/send message to whats app. Below is Sample code to send text message on Whats-app
Single user
private void shareToOneWhatsAppUser(String message) {
/**
* NOTE:
* Message is shared with only one user at a time. and to navigate back to main application user need to click back button
*/
Intent whatsappIntent = new Intent(Intent.ACTION_SEND);
whatsappIntent.setType("text/plain");
whatsappIntent.setPackage("com.whatsapp");
whatsappIntent.putExtra(Intent.EXTRA_TEXT, message);
//Directly send to specific mobile number...
String smsNumber = "919900990099";//Number without with country code and without '+' prifix
whatsappIntent.putExtra("jid", smsNumber + "#s.whatsapp.net"); //phone number without "+" prefix
if (whatsappIntent.resolveActivity(getPackageManager()) == null) {
Toast.makeText(MainActivity.this, "Whatsapp not installed.", Toast.LENGTH_SHORT).show();
return;
}
startActivity(whatsappIntent);
}
Multiple user
private void shareToMultipleWhatsAppUser(String message) {
/**
* NOTE:
*
* If want to send same message to multiple users then have to select the user to whom you want to share the message & then click send.
* User navigate back to main Application once he/she select all desired persons and click send button.
* No need to click Back Button!
*/
Intent whatsappIntent = new Intent(Intent.ACTION_SEND);
whatsappIntent.setType("text/plain");
whatsappIntent.setPackage("com.whatsapp");
whatsappIntent.putExtra(Intent.EXTRA_TEXT, message);
if (whatsappIntent.resolveActivity(getPackageManager()) == null) {
Toast.makeText(MainActivity.this, "Whatsapp not installed.", Toast.LENGTH_SHORT).show();
return;
}
startActivity(whatsappIntent);
}
One more way to achieve the same
private void shareDirecctToSingleWhatsAppUser(String message) {
/**
* NOTE:
* Message is shared with only one user at a time. and to navigate back to main application user need to click back button
*/
//Directly send to specific mobile number...
String smsNumber = "919900000000";//Intended user`s mobile number with country code & with out '+'
PackageManager packageManager = getPackageManager();
Intent i = new Intent(Intent.ACTION_VIEW);
try {
String url = "https://api.whatsapp.com/send?phone="+ smsNumber +"&text=" + URLEncoder.encode("Test Message!", "UTF-8");
i.setPackage("com.whatsapp");
i.setData(Uri.parse(url));
if (i.resolveActivity(packageManager) != null) {
startActivity(i);
}
} catch (Exception e){
e.printStackTrace();
}
}
you can use this code:
Intent sendIntent = new Intent("android.intent.action.MAIN");
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.setPackage("com.whatsapp");
sendIntent.setType("text/plain");
sendIntent.putExtra("jid", "9194******22" + "#s.whatsapp.net");// here 91 is country code
sendIntent.putExtra(Intent.EXTRA_TEXT, "Demo test message");
startActivity(sendIntent);
This is the best way to send Message through Whatsapp to specific number or unsaved number
private void openWhatsApp() {
String smsNumber = "252634651588";
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(getContext(), "WhatsApp not Installed",
Toast.LENGTH_SHORT).show();
startActivity(goToMarket);
}
}
private boolean whatsappInstalledOrNot(String uri) {
PackageManager pm = Objects.requireNonNull(getContext()).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;
}
This is what works for me.
The parameter 'body' gets not red by the whatsapp app, use 'Intent.EXTRA_TEXT' instead.
By setting the 'phoneNumber' you specify the contact to open in whatsapp.
Intent sendIntent = new Intent(Intent.ACTION_SENDTO,
Uri.parse("smsto:" + "" + phoneNumber + "?body=" + encodedMessage));
sendIntent.putExtra(Intent.EXTRA_TEXT, message);
sendIntent.setPackage("com.whatsapp");
startActivity(sendIntent);
Uri mUri = Uri.parse("smsto:+90000900000");
Intent mIntent = new Intent(Intent.ACTION_SENDTO, mUri);
mIntent.setPackage("com.whatsapp");
mIntent.putExtra("chat",true);
startActivity(Intent.createChooser(mIntent, "Share with"));
Works great to send message to specific contact on WhatsApp from my android app
Try this code
Uri uri = Uri.parse("smsto:" + "+6281122xxx");
Intent i = new Intent(Intent.ACTION_SENDTO, uri);
i.putExtra(Intent.EXTRA_TEXT, getResources().getString(R.string.default_message_wa));
i.setPackage("com.whatsapp");
startActivity(Intent.createChooser(i, ""));
You can't put string directly on putExtra like this
i.putExtra(Intent.EXTRA_TEXT, "YOUR TEXT");
Change your code and get string from resource like this
i.putExtra(Intent.EXTRA_TEXT, getResources().getString(R.string.default_message_wa));
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_VIEW);
String url ="https://wa.me/your number";
sendIntent.setData(Uri.parse(url));
startActivity(sendIntent);
Here's my way to do it (more here):
First, if you want to be sure you can send the message, you can check if the person has a WhatsApp account on the address book:
#RequiresPermission(permission.READ_CONTACTS)
public String getContactMimeTypeDataId(#NonNull Context context, String contactId, #NonNull String mimeType) {
if (TextUtils.isEmpty(mimeType) || !PermissionUtil.hasPermissions(context, Manifest.permission.READ_CONTACTS))
return null;
ContentResolver cr = context.getContentResolver();
Cursor cursor = cr.query(ContactsContract.Data.CONTENT_URI, new String[]{Data._ID}, Data.MIMETYPE + "= ? AND "
+ ContactsContract.Data.CONTACT_ID + "= ?", new String[]{mimeType, contactId}, null);
if (cursor == null)
return null;
if (!cursor.moveToFirst()) {
cursor.close();
return null;
}
String result = cursor.getString(cursor.getColumnIndex(Data._ID));
cursor.close();
return result;
}
and if all seem well, you open it as if it's from the web:
final String contactMimeTypeDataId = getContactMimeTypeDataId(context, contactId, "vnd.android.cursor.item/vnd.com.whatsapp.profile");
if (contactMimeTypeDataId != null) {
final String whatsAppPhoneNumber = PhoneNumberHelper.normalizePhone(phoneNumber);
String url = "https://api.whatsapp.com/send?phone="+ whatsAppPhoneNumber ;
intent = new Intent(Intent.ACTION_VIEW,Uri.parse(url));
intent.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT | Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET | Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP)
.setPackage("com.whatsapp");
startActivity(intent);
}
You can also check if WhatsApp is even installed before of all of this (or remove the setPackage and check if any app can handle the Intent) :
final PackageManager packageManager = context.getPackageManager();
final ApplicationInfo applicationInfo = packageManager.getApplicationInfo("com.whatsapp", 0);
if (applicationInfo == null)
return;
EDIT: about preparing the Intent with the Uri, I think this way is better:
#JvmStatic
fun prepareWhatsAppMessageIntent(normalizedPhoneNumber: String?, message: String? = null): Intent {
// example url: "https://api.whatsapp.com/send?phone=normalizedPhoneNumber&text=abc"
val builder = Uri.Builder().scheme("https").authority("api.whatsapp.com").path("send")
normalizedPhoneNumber?.let { builder.appendQueryParameter("phone", it) }
message?.let { builder.appendQueryParameter("text", it) }
return Intent(Intent.ACTION_VIEW, builder.build())
}
or alternative (based on here):
fun prepareWhatsAppMessageIntent(normalizedPhoneNumber: String?, message: String? = null): Intent {
// example url: "https://wa.me/normalizedPhoneNumber&text=abc"
val builder = Uri.Builder().scheme("https").authority("wa.me")
normalizedPhoneNumber?.let { builder.appendPath(it) }
message?.let { builder.appendQueryParameter("text", it) }
return Intent(Intent.ACTION_VIEW, builder.build())
}
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.

Categories

Resources