Opening a WhatsApp chat with a specific contact by clicking on a button in my app (Kotlin) - android

How can I Open a Whatsapp chat with a specific contact by clicking on a button in my app?
That's the code I use. It opens WhatsApp and let me search the contact I want to send the message to, but it doesn't open the WhatsApp chat with the specific contact number I gave it to.
whatsappButton.setOnClickListener{
var con = itemView.context
val textToShare = "*כח אדם*"
val phoneNumber = blogPost.phone
val sendIntent = Intent()
sendIntent.action = Intent.ACTION_SEND
sendIntent.type = "text/plain"
sendIntent.putExtra("jid", phoneNumber+"#s.whatsapp.net")
sendIntent.putExtra(Intent.EXTRA_TEXT, textToShare)
val extra = sendIntent.extras
startActivity(con,sendIntent,extra)
}

If you want send a message to a specific contact from Contacts app, you should first require permission to access contacts, get the number and try with this:
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);
Ref: https://stackoverflow.com/a/40285262/2895571

Please check this answer here
Use the following bit of code:
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);

First option: using Uri to convert whatsapp web url into button:
open_whatsapp.setOnClickListener {
val url = "https://api.whatsapp.com/send?phone=XXXXXXXXXX"
val openWhatsappIntent = Intent(Intent.ACTION_VIEW)
openWhatsappInten.data = Uri.parse(url)
startActivity(openWhatsappInten)
}
Second option; this is used as a href in web development :
Tel: XXX XXXX XX
maybe you can add Html format into TextView (Html.fromHtml()) and enable links clickeable to open the whatsapp application.

if you want send message to particular contact in whatsapp , use below url and particular mobile no to the Intent(including Country code).
String url = "https://wa.me/";
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url+mobile_no));
startActivity(browserIntent);

Related

Open mail app via intent doesn't open chooser

I'm trying to open an mail application on Android via intent. The purpose is to have a button in the app that will open your mail inbox. However when I use:
val intent = Intent(Intent.ACTION_MAIN)
intent.addCategory(Intent.CATEGORY_APP_EMAIL)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
startActivity(Intent.createChooser(intent, "Email"))
It always opens gmail, while I also have Outlook installed. The only way I get to choose between the mail apps is when yo use the mailto. But I don't intent to send an email, so it is not desired to use that intent.
Doesn't Outlook support this Intent?
use the following snippet to open to outlook directly from a different app
context.startActivity(
Intent().apply {
action = Intent.ACTION_MAIN
addCategory(Intent.CATEGORY_LAUNCHER)
component = ComponentName(
outlookLaunchIntent?.component?.packageName,
outlookLaunchIntent?.component?.className
)
setPackage(outlookLaunchIntent.package)
}
)
com.microsoft.office.outlook is the package name for outlook
For sending it to all email clients use a uri like this
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri data = Uri.parse("mailto:?subject=" + subject + "&body=" + body);
intent.setData(data);
startActivity(intent);
Ref:How to open Email program via Intents (but only an Email program)

How to send message to particular whatsapp contact programmatically using intent? [duplicate]

This question already has answers here:
Send text to specific contact programmatically (whatsapp)
(29 answers)
Closed 6 years ago.
I searched various answers but all of them are outdated.
Whenever I tried using send to it only opens contact chooser.
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.
You have to set the package name in the Intent like this
intent.setPackage("com.whatsapp");
Full example:
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);
You just fire the below intent on the click on button:
Uri mUri = Uri.parse("smsto:" + mobile1);
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(Intent.createChooser(mIntent, ""));
if number available on whatsapp then that particular user chat open and you send your message.If number not available on whatsapp the alert diaolge open in that case.
hope this help you ;-)
Here is solution
private void openWhatsApp(String number) {
String whatsAppMessage = "Hello!";
Uri uri = Uri.parse("smsto:" + number);
Intent i = new Intent(Intent.ACTION_SENDTO, uri);
i.setPackage("com.whatsapp");
startActivity(i);
}
Call above function and pass number, by which by want to open chat in Whatsapp messenger.
Hope it will work for you. :)

Choose among SMS, WhatsApp, or Telegram to send message

At a contact list in my Android app, there is an option to launch WhatsApp implemented as follows:
// Country code is required
final String phoneNumber = "+15555555555";
final String packageName = "com.whatsapp";
Intent intent = getPackageManager().getLaunchIntentForPackage(packageName);
if (null == intent) {
// Launch Google Play at WhatsApp homepage
intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("market://details?id=" + MESSAGE_PACKAGE_NAME));
startActivity(intent);
return;
}
intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + phoneNumber));
intent.setPackage(packageName);
startActivity(intent);
but this only allow me to send messages through WhatsApp.
Removing the package name and setting the intent type to
intent.setType("vnd.android-dir/mms-sms");
launched the SMS application.
How can we choose among all apps installed at an Android device that use the phone number as and identifier (Hangouts, SMS, Skype, Line, Telegram, Viber, WhatsApp, etc)?
Fortunately Android Intent.createChooser is smart enough to figure out the apps that understand the phone numbers as an identifier :-)
// Country code is required
String phoneNumber = "+15555555555";
Uri uri = Uri.parse("smsto:" + phoneNumber);
Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
startActivity(Intent.createChooser(intent, "Send message"));

Android Intent Chooser to only show E-mail option

My app integrates e-mail where the user can submit a bug report, feedback, etc. from the app directly. I'm using the application/octet-stream as the SetType for the Intent. When you go to submit the e-mail you get the content chooser and it shows various items from Evernote, Facebook, E-mail, etc.
How can I get this chooser to only show E-mail so as not to confuse the user with all these other items that fit the content chooser type?
Thank you.
To solve this issue simply follow the official documentation. The most important consideration are:
The flag is ACTION_SENDTO, and not ACTION_SEND.
The setData of method of the intent,
intent.setData(Uri.parse("mailto:")); // only email apps should handle this
If you send an empty Extra, the if() at the end won't work and the app won't launch the email client.
This works for me. According to Android documentation. If you want to ensure that your intent is handled only by an email app (and not other text messaging or social apps), then use the ACTION_SENDTO action and include the "mailto:" data scheme. For example:
public void composeEmail(String[] addresses, String subject) {
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setData(Uri.parse("mailto:")); // only email apps should handle this
intent.putExtra(Intent.EXTRA_EMAIL, addresses);
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}
https://developer.android.com/guide/components/intents-common.html#Email
I am presuming that you are using the ACTION_SEND Intent action, since you did not bother to actually state what you're using, but you agreed with #Aleadam's comment.
I'm using the application/octet-stream as the SetType for the Intent.
Nothing in that sentence limits things to email.
ACTION_SEND is a generic Intent action that can be supported by any application that wants to. All you do is indicate what data you are sharing and the MIME type of that data -- from there, it is up to the user to choose from available activities.
As #Jasoon indicates, you can try message/rfc822 as the MIME type. However, that is not indicating "only offer email clients" -- it indicates "offer anything that supports message/rfc822 data". That could readily include some application that are not email clients.
If you specifically want to send something by email, integrate JavaMail into your app, or write an email forwarding script on your Web server and invoke it, or something. If you use ACTION_SEND, you are implicitly stating that it is what the user wants that matters, and you want the user to be able to send such-and-so data by whatever means the user chooses.
Just struggled with this problem while implementing a Magic Link feature, a chooser intent for all installed email apps:
Chooser Intent Screenshot
private void openEmailApp() {
List<Intent> emailAppLauncherIntents = new ArrayList<>();
//Intent that only email apps can handle:
Intent emailAppIntent = new Intent(Intent.ACTION_SENDTO);
emailAppIntent.setData(Uri.parse("mailto:"));
emailAppIntent.putExtra(Intent.EXTRA_EMAIL, "");
emailAppIntent.putExtra(Intent.EXTRA_SUBJECT, "");
PackageManager packageManager = getPackageManager();
//All installed apps that can handle email intent:
List<ResolveInfo> emailApps = packageManager.queryIntentActivities(emailAppIntent, PackageManager.MATCH_ALL);
for (ResolveInfo resolveInfo : emailApps) {
String packageName = resolveInfo.activityInfo.packageName;
Intent launchIntent = packageManager.getLaunchIntentForPackage(packageName);
emailAppLauncherIntents.add(launchIntent);
}
//Create chooser
Intent chooserIntent = Intent.createChooser(new Intent(), "Select email app:");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, emailAppLauncherIntents.toArray(new Parcelable[emailAppLauncherIntents.size()]));
startActivity(chooserIntent);
}
There is a way more generic to do that, working with any MIME type.
See this post: How to customize share intent in Android?
It is possible to limit the choices of an intent chooser to just a few options. The code in the answer to this question is a good example. In essence, you would have to create a List of LabeledIntents to provide to the intent chooser, that will then include it in its list. Note that this solution works not on exclusion (certain apps are excluded while the rest remain) but instead you have to pick which apps to display. Hope it helps!
It works on all devices. It will show only Email Apps
public static void shareViaMail(Activity activity, String title, String body, String filePath) {
Uri URI = Uri.parse("file://" + filePath);
final Intent emailIntent = new Intent(Intent.ACTION_VIEW);
emailIntent.setData(Uri.parse("mailto:"));
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{"contact#brightsociety.com"});
if (URI != null) {
emailIntent.putExtra(Intent.EXTRA_STREAM, URI);
}
try {
activity.startActivity(emailIntent);
} catch (Exception e) {
((BaseActivity) activity).showToast("Gmail App is not installed");
e.printStackTrace();
}
}
Kotlin Answer
If you need to show only email apps and then you want to open only inbox (not open new email writing), you need to do A and B:
A) Add below code in your AndroidManifest.xml file for Android 11 because of package visibility update of Android 11 :
<queries>
<intent>
<action android:name="android.intent.action.SENDTO" />
<data android:scheme="mailto" />
</intent>
<intent>
<action android:name="android.intent.action.CHOOSER" />
</intent>
</queries>
B) Use below function to show email chooser:
// Show email app list.
fun showEmailAppList() {
// Email app list.
val emailAppLauncherIntents: MutableList<Intent?> = ArrayList()
// Create intent which can handle only by email apps.
val emailAppIntent = Intent(Intent.ACTION_SENDTO)
emailAppIntent.data = Uri.parse("mailto:")
// Find from all installed apps that can handle email intent and check version.
val emailApps = packageManager.queryIntentActivities(
emailAppIntent,
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) 0 else PackageManager.MATCH_ALL
)
// Collect email apps and put in intent list.
for (resolveInfo in emailApps) {
val packageName = resolveInfo.activityInfo.packageName
val launchIntent = packageManager.getLaunchIntentForPackage(packageName)
emailAppLauncherIntents.add(launchIntent)
}
// Create chooser with created intent list to show email apps of device.
val chooserIntent = Intent.createChooser(Intent(), "OPEN EMAIL APP")
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, emailAppLauncherIntents.toTypedArray())
startActivity(chooserIntent)
}
Result:
It works on all devices.It will show only Email Apps
public static void shareViaMail(Activity activity, String title, String body, String filePath) {
Uri URI = Uri.parse("file://" + filePath);
final Intent emailIntent = new Intent(Intent.ACTION_VIEW);
emailIntent.setData(Uri.parse("mailto:"));
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{"xyz#gmail.com"});
/*if you want to attach something*/
if (URI != null) {
emailIntent.putExtra(Intent.EXTRA_STREAM, URI);
}
try {
activity.startActivity(emailIntent);
} catch (Exception e) {
((BaseActivity) activity).showToast("Gmail App is not installed");
e.printStackTrace();
}
}
Solution is very simple:
Intent testIntent = new Intent(Intent.ACTION_VIEW);
Uri data = Uri.parse("mailto:?subject=" + "blah blah subject" + "&body=" + "blah blah body" + "&to=" + "sendme#me.com");
testIntent.setData(data);
startActivity(testIntent);
See: http://www.gaanza.com/blog/email-client-intent-android/
After a lot of searching and testing, I finally found a perfect solution. Thanks to the Open source developer, cketti for sharing his/her concise and neat solution.
String mailto = "mailto:bob#example.org" +
"?cc=" + "alice#example.com" +
"&subject=" + Uri.encode(subject) +
"&body=" + Uri.encode(bodyText);
Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
emailIntent.setData(Uri.parse(mailto));
try {
startActivity(emailIntent);
} catch (ActivityNotFoundException e) {
//TODO: Handle case where no email app is available
}
And this is the link to his/her gist.

Share application "link" in Android

I want my application user to be able to share/recommend my app to other users. I use the ACTION_SEND intent. I add plain text saying something along the lines of: install this cool application. But I can't find a way to enable users to directly go to the install screen of market place for instance. All I can provide them with is a web link or some text.
In other words I am looking for a very direct way for android users to have my app installed.
Thanks for any help/pointers,
Thomas
This will let you choose from email, whatsapp or whatever.
try {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_SUBJECT, "My application name");
String shareMessage= "\nLet me recommend you this application\n\n";
shareMessage = shareMessage + "https://play.google.com/store/apps/details?id=" + BuildConfig.APPLICATION_ID +"\n\n";
shareIntent.putExtra(Intent.EXTRA_TEXT, shareMessage);
startActivity(Intent.createChooser(shareIntent, "choose one"));
} catch(Exception e) {
//e.toString();
}
You can use also ShareCompat class from support library.
ShareCompat.IntentBuilder.from(activity)
.setType("text/plain")
.setChooserTitle("Chooser title")
.setText("http://play.google.com/store/apps/details?id=" + activity.getPackageName())
.startChooser();
https://developer.android.com/reference/android/support/v4/app/ShareCompat.html
Thomas,
You would want to provide your users with a market:// link which will bring them directly to the details page of your app. The following is from developer.android.com:
Loading an application's Details page
In Android Market, every application
has a Details page that provides an
overview of the application for users.
For example, the page includes a short
description of the app and screen
shots of it in use, if supplied by the
developer, as well as feedback from
users and information about the
developer. The Details page also
includes an "Install" button that lets
the user trigger the download/purchase
of the application.
If you want to refer the user to a
specific application, your
application can take the user directly
to the application's Details page. To
do so, your application sends an
ACTION_VIEW Intent that includes a URI
and query parameter in this format:
market://details?id=
In this case, the packagename
parameter is target application's
fully qualified package name, as
declared in the package attribute of
the manifest element in the
application's manifest file. For
example:
market://details?id=com.example.android.jetboy
Source: http://developer.android.com/guide/publishing/publishing.html
Call this method:
public static void shareApp(Context context)
{
final String appPackageName = context.getPackageName();
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "Check out the App at: https://play.google.com/store/apps/details?id=" + appPackageName);
sendIntent.setType("text/plain");
context.startActivity(sendIntent);
}
To be more exact
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("https://play.google.com/store/apps/details?id=com.android.example"));
startActivity(intent);
or if you want to share your other apps from your dev. account you can do something like this
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("https://play.google.com/store/apps/developer?id=Your_Publisher_Name"));
startActivity(intent);
To automatically fill in the application name and application id you could use this:
int applicationNameId = context.getApplicationInfo().labelRes;
final String appPackageName = context.getPackageName();
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_SUBJECT, activity.getString(applicationNameId));
String text = "Install this cool application: ";
String link = "https://play.google.com/store/apps/details?id=" + appPackageName;
i.putExtra(Intent.EXTRA_TEXT, text + " " + link);
startActivity(Intent.createChooser(i, "Share link:"));
Share application with title is you app_name, content is your application link
fun shareApp(context: Context) {
val appPackageName = BuildConfig.APPLICATION_ID
val appName = context.getString(R.string.app_name)
val shareBodyText = "https://play.google.com/store/apps/details?id=$appPackageName"
val sendIntent = Intent(Intent.ACTION_SEND).apply {
type = "text/plain"
putExtra(Intent.EXTRA_TITLE, appName)
putExtra(Intent.EXTRA_TEXT, shareBodyText)
}
context.startActivity(Intent.createChooser(sendIntent, null))
}
I know this question has been answered, but I would like to share an alternate solution:
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
String shareSubText = "WhatsApp - The Great Chat App";
String shareBodyText = "https://play.google.com/store/apps/details?id=com.whatsapp&hl=en";
shareIntent.putExtra(Intent.EXTRA_SUBJECT, shareSubText);
shareIntent.putExtra(Intent.EXTRA_TEXT, shareBodyText);
startActivity(Intent.createChooser(shareIntent, "Share With"));
finally, this code is worked for me to open the email client from android device.
try this snippet.
Intent testIntent = new Intent(Intent.ACTION_VIEW);
Uri data = Uri.parse("mailto:?subject=" + "Feedback" + "&body=" + "Write Feedback here....." + "&to=" + "someone#example.com");
testIntent.setData(data);
startActivity(testIntent);
Kotlin extension for share action. You can share whatever you want e.g. link
fun Context.share(text: String) =
this.startActivity(Intent().apply {
action = Intent.ACTION_SEND
putExtra(Intent.EXTRA_TEXT, text)
type = "text/plain"
})
Usage
context.share("Check https://stackoverflow.com")
According to official docs in 2021 preferred way is
fun shareTextToOtherApps(message: String) {
val sendIntent: Intent = Intent().apply {
action = Intent.ACTION_SEND
putExtra(Intent.EXTRA_TEXT, message)
type = "text/plain"
}
val shareIntent = Intent.createChooser(sendIntent, null)
startActivity(shareIntent)
}
Actually the best way to sheared you app between users , google (firebase) proved new technology Firebase Dynamic Link Through several lines you can make it
this is documentation
https://firebase.google.com/docs/dynamic-links/
and the code is
Uri dynamicLinkUri = dynamicLink.getUri();
Task<ShortDynamicLink> shortLinkTask = FirebaseDynamicLinks.getInstance().createDynamicLink()
.setLink(Uri.parse("https://www.google.jo/"))
.setDynamicLinkDomain("rw4r7.app.goo.gl")
.buildShortDynamicLink()
.addOnCompleteListener(this, new OnCompleteListener<ShortDynamicLink>() {
#Override
public void onComplete(#NonNull Task<ShortDynamicLink> task) {
if (task.isSuccessful()) {
// Short link created
Uri shortLink = task.getResult().getShortLink();
Uri flowchartLink = task.getResult().getPreviewLink();
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_TEXT, shortLink.toString());
intent.setType("text/plain");
startActivity(intent);
} else {
// Error
// ...
}
}
});
try {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_SUBJECT, "Your Application name");
String shareMessage= "\n Your Message \n\n";
shareMessage = shareMessage + "https://play.google.com/store/apps/details?id=" + BuildConfig.APPLICATION_ID +"\n\n";
shareIntent.putExtra(Intent.EXTRA_TEXT, shareMessage);
startActivity(Intent.createChooser(shareIntent, "choose one"));
} catch(Exception e) {
//e.toString();
}
#Linh answer is almost good but causing a crash because of the missing FLAG_ACTIVITY_NEW_TASK, here is what worked for me
public static void shareApp(Context context) {
final String appPackageName = context.getPackageName();
Intent sendIntent = new Intent();
sendIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "Check out the App at: https://play.google.com/store/apps/details?id=" + appPackageName);
sendIntent.setType("text/plain");
context.startActivity(sendIntent);
}

Categories

Resources