How to launch an Activity from another Application in Android - java

I want to launch an installed package from my Android application. I assume that it is possible using intents, but I didn't find a way of doing it. Is there a link, where to find the information?

If you don't know the main activity, then the package name can be used to launch the application.
Intent launchIntent = getPackageManager().getLaunchIntentForPackage("com.package.address");
if (launchIntent != null) {
startActivity(launchIntent);//null pointer check in case package name was not found
}

I know this has been answered but here is how I implemented something similar:
Intent intent = getPackageManager().getLaunchIntentForPackage("com.package.name");
if (intent != null) {
// We found the activity now start the activity
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
} else {
// Bring user to the market or let them choose an app?
intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setData(Uri.parse("market://details?id=" + "com.package.name"));
startActivity(intent);
}
Even better, here is the method:
public void startNewActivity(Context context, String packageName) {
Intent intent = context.getPackageManager().getLaunchIntentForPackage(packageName);
if (intent != null) {
// We found the activity now start the activity
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
} else {
// Bring user to the market or let them choose an app?
intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setData(Uri.parse("market://details?id=" + packageName));
context.startActivity(intent);
}
}
Removed duplicate code:
public void startNewActivity(Context context, String packageName) {
Intent intent = context.getPackageManager().getLaunchIntentForPackage(packageName);
if (intent == null) {
// Bring user to the market or let them choose an app?
intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("market://details?id=" + packageName));
}
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}

I found the solution. In the manifest file of the application I found the package name: com.package.address and the name of the main activity which I want to launch: MainActivity
The following code starts this application:
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setComponent(new ComponentName("com.package.address","com.package.address.MainActivity"));
startActivity(intent);

// in onCreate method
String appName = "Gmail";
String packageName = "com.google.android.gm";
openApp(context, appName, packageName);
public static void openApp(Context context, String appName, String packageName) {
if (isAppInstalled(context, packageName))
if (isAppEnabled(context, packageName))
context.startActivity(context.getPackageManager().getLaunchIntentForPackage(packageName));
else Toast.makeText(context, appName + " app is not enabled.", Toast.LENGTH_SHORT).show();
else Toast.makeText(context, appName + " app is not installed.", Toast.LENGTH_SHORT).show();
}
private static boolean isAppInstalled(Context context, String packageName) {
PackageManager pm = context.getPackageManager();
try {
pm.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES);
return true;
} catch (PackageManager.NameNotFoundException ignored) {
}
return false;
}
private static boolean isAppEnabled(Context context, String packageName) {
boolean appStatus = false;
try {
ApplicationInfo ai = context.getPackageManager().getApplicationInfo(packageName, 0);
if (ai != null) {
appStatus = ai.enabled;
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return appStatus;
}

Edit depending on comment
In some versions - as suggested in comments - the exception thrown may be different.
Thus the solution below is slightly modified
Intent launchIntent = null;
try{
launchIntent = getPackageManager().getLaunchIntentForPackage("applicationId");
} catch (Exception ignored) {}
if(launchIntent == null){
startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("https://play.google.com/store/apps/details?id=" + "applicationId")));
} else {
startActivity(launchIntent);
}
Original Answer
Although answered well, there is a pretty simple implementation that handles if the app is not installed. I do it like this
try{
startActivity(getPackageManager().getLaunchIntentForPackage("applicationId"));
} catch (PackageManager.NameNotFoundException e) {
startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("https://play.google.com/store/apps/details?id=" + "applicationId")));
}
Replace "applicationId" with the package that you want to open such as com.google.maps, etc.

Here is my example of launching bar/QR code scanner from my app if someone finds it useful
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.setPackage("com.google.zxing.client.android");
try
{
startActivityForResult(intent, SCAN_REQUEST_CODE);
}
catch (ActivityNotFoundException e)
{
//implement prompt dialog asking user to download the package
AlertDialog.Builder downloadDialog = new AlertDialog.Builder(this);
downloadDialog.setTitle(stringTitle);
downloadDialog.setMessage(stringMessage);
downloadDialog.setPositiveButton("yes",
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialogInterface, int i)
{
Uri uri = Uri.parse("market://search?q=pname:com.google.zxing.client.android");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
try
{
myActivity.this.startActivity(intent);
}
catch (ActivityNotFoundException e)
{
Dialogs.this.showAlert("ERROR", "Google Play Market not found!");
}
}
});
downloadDialog.setNegativeButton("no",
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int i)
{
dialog.dismiss();
}
});
downloadDialog.show();
}

If you want to open specific activity of another application we can use this.
Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
final ComponentName cn = new ComponentName("com.android.settings", "com.android.settings.fuelgauge.PowerUsageSummary");
intent.setComponent(cn);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try
{
startActivity(intent)
}catch(ActivityNotFoundException e){
Toast.makeText(context,"Activity Not Found",Toast.LENGTH_SHORT).show()
}
If you must need other application, instead of showing Toast you can show a dialog. Using dialog you can bring the user to Play-Store to download required application.

Check for the app, avoiding any crashes. If the app exists in the phone then it will be launched, otherwise it will search in Google Play. If no Google Play app installed in the phone, it will search in the Google Play Store via browser:
public void onLunchAnotherApp() {
final String appPackageName = getApplicationContext().getPackageName();
Intent intent = getPackageManager().getLaunchIntentForPackage(appPackageName);
if (intent != null) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
} else {
onGoToAnotherInAppStore(intent, appPackageName);
}
}
public void onGoToAnotherInAppStore(Intent intent, String appPackageName) {
try {
intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setData(Uri.parse("market://details?id=" + appPackageName));
startActivity(intent);
} catch (android.content.ActivityNotFoundException anfe) {
intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setData(Uri.parse("http://play.google.com/store/apps/details?id=" + appPackageName));
startActivity(intent);
}
}

Starting from API 30 (Android 11) you can receive nullpointerexception with launchIntentForPackage
val launchIntent: Intent? = activity.packageManager.getLaunchIntentForPackage("com.google.android.gm")
startActivity(launchIntent)
To avoid this you need to add the needed package to the manifest
<queries>
<package android:name="com.google.android.gm" />
</queries>
Here is documentation
https://developer.android.com/training/package-visibility
And the medium article
https://medium.com/androiddevelopers/package-visibility-in-android-11-cc857f221cd9

It is possible to start an app's activity by using Intent.setClassName according to the docs.
An example:
val activityName = "com.google.android.apps.muzei.MuzeiActivity" // target activity name
val packageName = "net.nurik.roman.muzei" // target package's name
val intent = Intent().setClassName(packageName, activityName)
startActivity(intent)
To open it outside the current app, add this flag before starting the intent.
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
A related answer here

If you know the data and the action the installed package react on, you simply should add these information to your intent instance before starting it.
If you have access to the AndroidManifest of the other app, you can see all needed information there.

Steps to launch new activity as follows:
1.Get intent for package
2.If intent is null redirect user to playstore
3.If intent is not null open activity
public void launchNewActivity(Context context, String packageName) {
Intent intent = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.CUPCAKE) {
intent = context.getPackageManager().getLaunchIntentForPackage(packageName);
}
if (intent == null) {
try {
intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setData(Uri.parse("market://details?id=" + packageName));
context.startActivity(intent);
} catch (android.content.ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + packageName)));
}
} else {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
}

private fun openOtherApp() {
val sendIntent = packageManager.getLaunchIntentForPackage("org.mab.dhyanaqrscanner")
startActivity(sendIntent)
finishAffinity()
}

This will cover all scenarios
1.Get intent for package
2.If intent is null redirect user to playstore
3.If there is an issue with open playstore, then it opens on the default browser.
var intent = activity!!.packageManager.getLaunchIntentForPackage("com.google.android.youtube")
if (intent == null) {
if (intent == null) {
intent = try {
Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=com.google.android.youtube"))
} catch (e: Exception) {
Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=com.google.android.youtube"))
}
}
startActivity(intent)
For Android 11 (API level 30) or higher, in AndroidManifest.xml,
<queries>
<package android:name="com.google.android.youtube" />
<package android:name="com.example.app" />
</queries>
Or simply we can allow for all packages (not recommended)
<uses-permission android:name="android.permission.QUERY_ALL_PACKAGES" tools:ignore="QueryAllPackagesPermission" />
References
Package visibility filtering on Android
Declaring package visibility needs

Try code below:
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setComponent(new ComponentName("package_name", "Class_name"));
if (intent.resolveActivity(getPackageManager()) != null)
{
startActivity(intent);
}

In Kotlin
fun openApplicationOrMarket(packageName: String) {
var intent = requireContext().packageManager.getLaunchIntentForPackage(packageName)
if (intent == null) {
intent = Intent(Intent.ACTION_VIEW)
intent.data = Uri.parse("market://details?id=$packageName")
}
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
requireContext().startActivity(intent)
}

Pass the package name and the message you want to show if package isn't installed ;-)
void openApp(String appPackageName,String message){
Intent launchIntent = getPackageManager().getLaunchIntentForPackage(appPackageName);
if (launchIntent != null) {
startActivity(launchIntent);
} else {
Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackageName)));
}
}

Since kotlin is becoming very popular these days, I think it's appropriate to provide a simple solution in Kotlin as well.
var launchIntent: Intent? = null
try {
launchIntent = packageManager.getLaunchIntentForPackage("applicationId")
} catch (ignored: Exception) {
}
if (launchIntent == null) {
startActivity(Intent(Intent.ACTION_VIEW).setData(Uri.parse("https://play.google.com/store/apps/details?id=" + "applicationId")))
} else {
startActivity(launchIntent)
}

Related

Why the Share Tray Labeled Intent LinkedIn Icon not displayed while sharing content in Android 10 OS

I am sharing plain/text via Intent share using Share tray read the package name from and filter the App in labeled intent. Some application is showing in that list and have Linkedin package name also in that list but not showing the Linkedin icon in share tray. Why that icon not displayed?
Device: Samsung Galaxy S10
OS: Android Version 10
Code which I Tried
PackageManager pm=getActivityContext.getPackageManager();
Intent sendIntent=new Intent(Intent.ACTION_SEND);
sendIntent.setType("text/plain");
Intent receiver=new Intent(getActivityContext, UserSelectedShareBroadcast.class);
PendingIntent pendingIntent=PendingIntent.getBroadcast(getActivityContext, 0, receiver, PendingIntent.FLAG_UPDATE_CURRENT);
Intent openInChooser=Intent.createChooser(emailIntent, "Choose", pendingIntent.getIntentSender());
List<ResolveInfo> resInfo=pm.queryIntentActivities(sendIntent, 0);
List<LabeledIntent> intentList=new ArrayList<>();
Intent externalEmailIntent=new Intent(getActivityContext, ExternalEmailShareActivity.class);
externalEmailIntent.putExtra("programId", programId);
intentList.add(new LabeledIntent(externalEmailIntent, "packagename", "Email to", R.drawable.ic_mail_outline));
for (int i=0; i < resInfo.size(); i++) {
// Extract the label, append it, and repackage it in a LabeledIntent
ResolveInfo ri=resInfo.get(i);
String packageName=ri.activityInfo.packageName;
//Enabled Tweet sharing
/*if (packageName.contains("twitter")) {
emailIntent.setPackage(packageName);
} else*/
if (packageName.contains("twitter") || packageName.contains("facebook") ||
packageName.contains("whatsapp") || packageName.contains("linkedin") ||
packageName.contains("com.google.android.apps.docs") ||
packageName.contains("com.google.android.gm") ||
packageName.contains("com.Slack")) {
Intent intent=new Intent();
try {
intent.setComponent(new ComponentName(packageName, ri.activityInfo.name));
intent.setAction(Intent.ACTION_SEND);
intent.setType("text/plain");
//intent.setType("text/plain/image");
if (packageName.contains("twitter")) {
intent.putExtra(Intent.EXTRA_TEXT, sharedURL);
} else if (packageName.contains("facebook")) {
// Warning: Facebook IGNORES our text. They say "These fields are intended for users to express themselves. Pre-filling these fields erodes the authenticity of the user voice."
// One workaround is to use the Facebook SDK to post, but that doesn't allow the user to choose how they want to share. We can also make a custom landing page, and the link
// will show the <meta content ="..."> text from that page with our link in Facebook.
intent.putExtra(Intent.EXTRA_TEXT, sharedURL);
} else if (packageName.contains("whatsapp")) {
intent.putExtra(Intent.EXTRA_TEXT, sharedURL);
} else if (packageName.contains("linkedin")) {
intent.putExtra(Intent.EXTRA_TEXT, sharedURL);
} else if (packageName.contains("com.google.android.apps.docs")) {
intent.putExtra(Intent.EXTRA_TEXT, sharedURL);
} else if (packageName.contains("com.Slack")) {
intent.putExtra(Intent.EXTRA_TEXT, sharedURL);
}else if (packageName.contains("android.gm")) {
// If Gmail shows up twice, try removing this else-if clause and the reference to "android.gm" above
//intent.putExtra(Intent.EXTRA_TEXT, Html.fromHtml(resources.getString(R.string.share_email_gmail)));
intent.putExtra(Intent.EXTRA_SUBJECT, str_title);
intent.setType("message/rfc822");
intent.putExtra(Intent.EXTRA_TEXT, sharedURL);
Uri uri = Uri.parse(publicThumbnail);
intent.putExtra(Intent.EXTRA_STREAM, uri);
}
intentList.add(new LabeledIntent(intent, packageName, ri.loadLabel(pm), ri.icon));
} catch (Exception e) {
e.printStackTrace();
} finally {
intent=null;
}
}
}
// convert intentList to array
LabeledIntent[] extraIntents=intentList.toArray(new LabeledIntent[intentList.size()]);
openInChooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraIntents);
getActivityContext.startActivityForResult(openInChooser, REQUEST_SHARED_URL);
I made some changes in your code to make post on LinkedIn via Intent. Please check my code which is given below. I have tested in android 10 os and it is working fine. hope it helps.
private void shareTray(){
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(Intent.EXTRA_TEXT, sharedURL);
Intent receiver=new Intent(getActivityContext, UserSelectedShareBroadcast.class);
PendingIntent pendingIntent=PendingIntent.getBroadcast(getActivityContext, 0, receiver, PendingIntent.FLAG_UPDATE_CURRENT);
PackageManager pm=getActivityContext.getPackageManager();
Intent openInChooser=Intent.createChooser(sharingIntent, "Choose", pendingIntent.getIntentSender());
List<ResolveInfo> resInfo=pm.queryIntentActivities(sharingIntent, 0);
List<LabeledIntent> intentList=new ArrayList<>();
Intent externalEmailIntent=new Intent(getActivityContext, ExternalEmailShareActivity.class);
externalEmailIntent.putExtra("INBOX", "Inbox");
intentList.add(new LabeledIntent(externalEmailIntent, "yourpackagename", "Email to", R.drawable.ic_mail_outline));
for (int i=0; i < resInfo.size(); i++) {
ResolveInfo ri=resInfo.get(i);
String packageName=ri.activityInfo.packageName;
if (packageName.contains("twitter")) {
sharingIntent.setPackage(packageName);
} else{
if (packageName.contains("twitter") || packageName.contains("facebook") ||
packageName.contains("whatsapp") || packageName.contains("linkedin") ||
packageName.contains("com.google.android.apps.docs") ||
packageName.contains("com.google.android.gm") ||
packageName.contains("com.Slack")) {
Intent shareIntent=new Intent();
try {
shareIntent.setComponent(new ComponentName(packageName, ri.activityInfo.name));
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
//shareIntent.setType("text/plain/image");
if (packageName.contains("twitter")) {
shareIntent.putExtra(Intent.EXTRA_TEXT, sharedURL);
} else if (packageName.contains("facebook")){shareIntent.putExtra(Intent.EXTRA_TEXT, sharedURL);
} else if (packageName.contains("whatsapp")) {
shareIntent.putExtra(Intent.EXTRA_TEXT, sharedURL);
} else if (packageName.contains("linkedin")) {
shareIntent.putExtra(Intent.EXTRA_TITLE, sharedURL);
shareIntent.putExtra(Intent.EXTRA_TEXT, sharedURL);
} else if (packageName.contains("com.google.android.apps.docs")) {
shareIntent.putExtra(Intent.EXTRA_TEXT, sharedURL);
} else if (packageName.contains("com.Slack")) {
shareIntent.putExtra(Intent.EXTRA_TEXT, sharedURL);
}else if (packageName.contains("android.gm")) {
// If Gmail shows up twice, try removing this else-if clause and the reference to "android.gm" above
shareIntent.putExtra(Intent.EXTRA_SUBJECT, str_title);
shareIntent.setType("message/rfc822");
shareIntent.putExtra(Intent.EXTRA_TEXT, sharedURL);
Uri uri = Uri.parse(publicThumbnail);
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
}
intentList.add(new LabeledIntent(shareIntent, packageName, ri.loadLabel(pm), ri.icon));
} catch (Exception e) {
e.printStackTrace();
} finally {
shareIntent=null;
}
}
}
}
// convert intentList to array
LabeledIntent[] extraIntents=intentList.toArray(new LabeledIntent[intentList.size()]);
openInChooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraIntents);
getActivityContext.startActivityForResult(openInChooser, REQUEST_SHARED_URL);
}
Happy Coding..

How to send the Pre-populated text message to specific (intended) Whats-App user / users? [duplicate]

Since I found some older posts, that tell that whatsapp doesn't support this, I was wondering if something had changed and if there is a way to open a whatsapp 'chat' with a number that I'm sending through an intent?
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
With this code you can open the whatsapp chat with the given number.
void openWhatsappContact(String number) {
Uri uri = Uri.parse("smsto:" + number);
Intent i = new Intent(Intent.ACTION_SENDTO, uri);
i.setPackage("com.whatsapp");
startActivity(Intent.createChooser(i, ""));
}
Simple solution, try this.
String phoneNumberWithCountryCode = "+62820000000";
String message = "Hallo";
startActivity(
new Intent(Intent.ACTION_VIEW,
Uri.parse(
String.format("https://api.whatsapp.com/send?phone=%s&text=%s", phoneNumberWithCountryCode, message)
)
)
);
I found the following solution, first you'll need the whatsapp id:
Matching with reports from some other threads here and in other forums the login name I found was some sort of:
international area code without the 0's or + in the beginning + phone number without the first 0 + #s.whatsapp.net
For example if you live in the Netherlands and having the phone number 0612325032 it would be 31612325023#s.whatsapp.net -> +31 for the Netherlands without the 0's or + and the phone number without the 0.
public void sendWhatsAppMessageTo(String whatsappid) {
Cursor c = getSherlockActivity().getContentResolver().query(ContactsContract.Data.CONTENT_URI,
new String[] { ContactsContract.Contacts.Data._ID }, ContactsContract.Data.DATA1 + "=?",
new String[] { whatsappid }, null);
c.moveToFirst();
Intent whatsapp = new Intent(Intent.ACTION_VIEW, Uri.parse("content://com.android.contacts/data/" + c.getString(0)));
c.close();
if (whatsapp != null) {
startActivity(whatsapp);
} else {
Toast.makeText(this, "WhatsApp not Installed", Toast.LENGTH_SHORT)
.show();
//download for example after dialog
Uri uri = Uri.parse("market://details?id=com.whatsapp");
Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
}
}
This should work whether Whatsapp is installed or not.
boolean isWhatsappInstalled = whatsappInstalledOrNot("com.whatsapp");
if (isWhatsappInstalled) {
Uri uri = Uri.parse("smsto:" + "98*********7")
Intent sendIntent = new Intent(Intent.ACTION_SENDTO, uri);
sendIntent.putExtra(Intent.EXTRA_TEXT, "Hai Good Morning");
sendIntent.setPackage("com.whatsapp");
startActivity(sendIntent);
} else {
Toast.makeText(this, "WhatsApp not Installed", Toast.LENGTH_SHORT).show();
Uri uri = Uri.parse("market://details?id=com.whatsapp");
Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
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;
}
Tested on Marshmallow S5 and it works!
Uri uri = Uri.parse("smsto:" + "phone number with country code");
Intent sendIntent = new Intent(Intent.ACTION_SENDTO, uri);
sendIntent.setPackage("com.whatsapp");
startActivity(sendIntent);
This will open a direct chat with a person, if whatsapp not installed this will throw exception, if phone number not known to whatsapp they will offer to send invite via sms or simple sms message
use this singleline code use to Sending message through WhatsApp
//NOTE : please use with country code first 2digits without plus signed
try {
String mobile = "911234567890";
String msg = "Its Working";
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://api.whatsapp.com/send?phone=" + mobile + "&text=" + msg)));
}catch (Exception e){
//whatsapp app not install
}
Here is the latest way to send a message via Whatsapp, even if the receiver's phone number is not in your Whatsapp chat or phone's Contacts list.
private fun openWhatsApp(number: String) {
try {
packageManager.getPackageInfo("com.whatsapp", PackageManager.GET_ACTIVITIES)
val intent = Intent(
Intent.ACTION_VIEW,
Uri.parse("https://wa.me/$number?text=I'm%20interested%20in%20your%20car%20for%20sale")
)
intent.setPackage("com.whatsapp")
startActivity(intent)
} catch (e: PackageManager.NameNotFoundException) {
Toast.makeText(
this,
"Whatsapp app not installed in your phone",
Toast.LENGTH_SHORT
).show()
e.printStackTrace()
}
}
intent.setPackage("com.whatsapp") will help you to avoid Open With chooser and open Whatsapp directly.
Importent Note: If You are ending in catch statement, even if Whatsapp is installed. Please add queries to manifest.xml as follows:
<queries>
<package android:name="com.whatsapp" />
</queries>
Please see this answer for more details.
To check if WhatsApp is installed in device and initiate "click to chat" in WhatsApp:
Kotlin:
try {
// Check if whatsapp is installed
context?.packageManager?.getPackageInfo("com.whatsapp", PackageManager.GET_META_DATA)
val intent = Intent(Intent.ACTION_VIEW, Uri.parse("https://wa.me/$internationalPhoneNumber"))
startActivity(intent)
} catch (e: NameNotFoundException) {
Toast.makeText(context, "WhatsApp not Installed", Toast.LENGTH_SHORT).show()
}
Java:
try {
// Check if whatsapp is installed
getPackageManager().getPackageInfo("com.whatsapp", PackageManager.GET_META_DATA);
Intent intent = Intent(Intent.ACTION_VIEW, Uri.parse("https://wa.me/" + internationalPhoneNumber));
startActivity(intent);
} catch (NameNotFoundException e) {
Toast.makeText(context, "WhatsApp not Installed", Toast.LENGTH_SHORT).show();
}
getPackageInfo() throws NameNotFoundException if WhatsApp is not installed.
The internationalPhoneNumber variable is used to access the phone number.
Reference:
https://faq.whatsapp.com/general/chats/how-to-use-click-to-chat?category=5245251
https://stackoverflow.com/a/2201999/9636037
https://stackoverflow.com/a/15931345/9636037
The following code is used by Google Now App and will NOT work for any other application.
I'm writing this post because it makes me angry, that WhatsApp does not allow any other developers to send messages directly except for Google.
And I want other freelance-developers to know, that this kind of cooperation is going on, while Google keeps talking about "open for anybody" and WhatsApp says they don't want to provide any access to developers.
Recently WhatsApp has added an Intent specially for Google Now, which should look like following:
Intent intent = new Intent("com.google.android.voicesearch.SEND_MESSAGE_TO_CONTACTS");
intent.setPackage("com.whatsapp");
intent.setComponent(new ComponentName("com.whatsapp", "com.whatsapp.VoiceMessagingActivity"));
intent.putExtra("com.google.android.voicesearch.extra.RECIPIENT_CONTACT_CHAT_ID", number);
intent.putExtra("android.intent.extra.TEXT", text);
intent.putExtra("search_action_token", ?????);
I could also find out that "search_action_token" is a PendingIntent
that contains an IBinder-Object, which is sent back to Google App and checked, if it was created by Google Now.
Otherwise WhatsApp will not accept the message.
Currently, the only official API that you may make a GET request to:
https://api.whatsapp.com/send?phone=919773207706&text=Hello
Anyways, there is a secret API program already being ran by WhatsApp
As the documentation says you can just use an URL like:
https://wa.me/15551234567
Where the last segment is the number in in E164 Format
Uri uri = Uri.parse("https://wa.me/15551234567");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
This is what worked for me :
Uri uri = Uri.parse("https://api.whatsapp.com/send?phone=" + "<number>" + "&text=" + "Hello WhatsApp!!");
Intent sendIntent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(sendIntent);
This works to me:
PackageManager pm = context.getPackageManager();
try {
pm.getPackageInfo("com.whatsapp", PackageManager.GET_ACTIVITIES);
Intent intent = new Intent();
intent.setComponent(new ComponentName(packageName,
ri.activityInfo.name));
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, element);
} catch (NameNotFoundException e) {
ToastHelper.MakeShortText("Whatsapp have not been installed.");
}
Use direct URL of whatsapp
String url = "https://api.whatsapp.com/send?phone="+number;
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
You'll want to use a URL in the following format...
https://api.whatsapp.com/send?text=text
Then you can have it send whatever text you'd like. You also have the option to specify a phone number...
https://api.whatsapp.com/send?text=text&phone=1234
What you CANNOT DO is use the following:
https://wa.me/send?text=text
You will get...
We couldn't find the page you were looking for
wa.me, though, will work if you supply both a phone number and text. But, for the most part, if you're trying to make a sharing link, you really don't want to indicate the phone number, because you want the user to select someone. In that event, if you don't supply the number and use wa.me as URL, all of your sharing links will fail. Please use app.whatsapp.com.
this is much lengthy but surly working.
enjoy your code:)
//method used to show IMs
private void show_custom_chooser(String value) {
List<ResolveInfo> list = null;
final Intent email = new Intent(Intent.ACTION_SEND);
email.setData(Uri.parse("sms:"));
email.putExtra(Intent.EXTRA_TEXT, "" + value);
email.setType("text/plain"); // vnd.android-dir/mms-sms
WindowManager.LayoutParams WMLP = dialogCustomChooser.getWindow()
.getAttributes();
WMLP.gravity = Gravity.CENTER;
dialogCustomChooser.getWindow().setAttributes(WMLP);
dialogCustomChooser.getWindow().setBackgroundDrawable(
new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialogCustomChooser.setCanceledOnTouchOutside(true);
dialogCustomChooser.setContentView(R.layout.about_dialog);
dialogCustomChooser.setCancelable(true);
ListView lvOfIms = (ListView) dialogCustomChooser
.findViewById(R.id.listView1);
PackageManager pm = getPackageManager();
List<ResolveInfo> launchables = pm.queryIntentActivities(email, 0);
// ////////////new
list = new ArrayList<ResolveInfo>();
for (int i = 0; i < launchables.size(); i++) {
String string = launchables.get(i).toString();
Log.d("heh", string);
//check only messangers
if (string.contains("whatsapp")) {
list.add(launchables.get(i));
}
}
Collections.sort(list, new ResolveInfo.DisplayNameComparator(pm));
int size = launchables.size();
adapter = new AppAdapter(pm, list, MainActivity.this);
lvOfIms.setAdapter(adapter);
lvOfIms.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
ResolveInfo launchable = adapter.getItem(position);
ActivityInfo activity = launchable.activityInfo;
ComponentName name = new ComponentName(
activity.applicationInfo.packageName, activity.name);
email.addCategory(Intent.CATEGORY_LAUNCHER);
email.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
email.setComponent(name);
startActivity(email);
dialogCustomChooser.dismiss();
}
});
dialogCustomChooser.show();
}
I'm really late here but I believe that nowadays we have shorter and better solutions to send messages through WhatsApp.
You can use the following to call the system picker, then choose which app you will use to share whatever you want.
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);
If you are really need to send through WhatsApp all you need to do is the following (You will skip the system picker)
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
sendIntent.setType("text/plain");
// Put this line here
sendIntent.setPackage("com.whatsapp");
//
startActivity(sendIntent);
If you need more information you can find it here: WhatsApp FAQ
private fun sendWhatsappMessage(phoneNumber:String, text:String) {
val url = if (Intent().setPackage("com.whatsapp").resolveActivity(packageManager) != null) {
"whatsapp://send?text=Hello&phone=$phoneNumber"
} else {
"https://api.whatsapp.com/send?phone=$phoneNumber&text=$text"
}
val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
startActivity(browserIntent)
}
This is a much easier way to achieve this. This code checks if whatsapp is installed on the device. If it is installed, it bypasses the system picker and goes to the contact on whatsapp and prefields the text in the chat. If not installed it opens whatsapp link on your web browser.
Sending to WhatsApp Number that exist in your contact list.
Notice that we are using ACTION_SEND
Intent whatsappIntent = new Intent(Intent.ACTION_SEND);
whatsappIntent.setType("text/plain");
whatsappIntent.setPackage("com.whatsapp");
whatsappIntent.putExtra(Intent.EXTRA_TEXT, "SMS TEXT, TEXT THAT YOU NEED TO SEND");
try {
startActivityForResult(whatsappIntent, 100);
} catch (Exception e) {
Toast.makeText(YourActivity.this, "App is not installed", Toast.LENGTH_SHORT).show();
}
If Number doesn't exist in contact list. Use WhatsApp API.
String number = number_phone.getText().toString(); // I toke it from Dialog box
number = number.substring(1); // To remove 0 at the begging of number (Optional) but needed in my case
number = "962" + number; // Replace it with your country code
String url = "https://api.whatsapp.com/send?phone=" + number + "&text=" + Uri.parse("Text that you want to send to the current user");
Intent whatsappIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
whatsappIntent.setPackage("com.whatsapp");
whatsappIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
context.startActivity(whatsappIntent);
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(YourActivity.this, "App is not installed", Toast.LENGTH_SHORT).show();
}
Check this code,
public void share(String subject,String text) {
final Intent intent = new Intent(Intent.ACTION_SEND);
String score=1000;
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, score);
intent.putExtra(Intent.EXTRA_TEXT, text);
startActivity(Intent.createChooser(intent, getString(R.string.share)));
}
This works to me:
public static void shareWhatsApp(Activity appActivity, String texto) {
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.setType("text/plain");
sendIntent.putExtra(android.content.Intent.EXTRA_TEXT, texto);
PackageManager pm = appActivity.getApplicationContext().getPackageManager();
final List<ResolveInfo> matches = pm.queryIntentActivities(sendIntent, 0);
boolean temWhatsApp = false;
for (final ResolveInfo info : matches) {
if (info.activityInfo.packageName.startsWith("com.whatsapp")) {
final ComponentName name = new ComponentName(info.activityInfo.applicationInfo.packageName, info.activityInfo.name);
sendIntent.addCategory(Intent.CATEGORY_LAUNCHER);
sendIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_NEW_TASK);
sendIntent.setComponent(name);
temWhatsApp = true;
break;
}
}
if(temWhatsApp) {
//abre whatsapp
appActivity.startActivity(sendIntent);
} else {
//alerta - você deve ter o whatsapp instalado
Toast.makeText(appActivity, appActivity.getString(R.string.share_whatsapp), Toast.LENGTH_SHORT).show();
}
}
get the contact number whom you want to send the message and create uri for whatsapp, here c is a Cursor returning the selected contact.
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);
From the documentation
To create your own link with a pre-filled message that will
automatically appear in the text field of a chat, use
https://wa.me/whatsappphonenumber/?text=urlencodedtext where
whatsappphonenumber is a full phone number in international format and
URL-encodedtext is the URL-encoded pre-filled message.
Example:https://wa.me/15551234567?text=I'm%20interested%20in%20your%20car%20for%20sale
Code example
val phoneNumber = "13492838472"
val text = "Hey, you know... I love StackOverflow :)"
val uri = Uri.parse("https://wa.me/$phoneNumber/?text=$text")
val sendIntent = Intent(Intent.ACTION_VIEW, uri)
startActivity(sendIntent)
This one worked finally for me in Kotlin:
private fun navigateToWhatsApp() {
try {
val url = "https://api.whatsapp.com/send?phone=+91${getString(R.string.contact)}"
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)).setPackage("com.whatsapp"))
} catch (e: Exception) {
showToast("Whatsapp app not installed in your device")
}
}
The following API can be used in c++ as shown in my article.
You need to define several constants:
//
#define    GroupAdmin                <YOUR GROUP ADMIN MOBILE PHONE>
#define GroupName                <YOUR GROUP NAME>
#define CLIENT_ID                <YOUR CLIENT ID>
#define CLIENT_SECRET            <YOUR CLIENT SECRET>
#define GROUP_API_SERVER        L"api.whatsmate.net"
#define GROUP_API_PATH          L"/v3/whatsapp/group/text/message/12"
#define IMAGE_SINGLE_API_URL    L"http://api.whatsmate.net/v3/whatsapp/group/image/message/12"
//
Then you connect to the API’s endpoint.
hOpenHandle = InternetOpen(_T("HTTP"), INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
if (hOpenHandle == NULL)
{
return false;
}
hConnectHandle = InternetConnect(hOpenHandle,
GROUP_API_SERVER,
INTERNET_DEFAULT_HTTP_PORT,
NULL, NULL, INTERNET_SERVICE_HTTP,
0, 1);
if (hConnectHandle == NULL)
{
InternetCloseHandle(hOpenHandle);
return false;
}
Then send both header and body and wait for the result that needs to be “OK”.
Step 1 - open an HTTP request:
const wchar_t *AcceptTypes[] = { _T("application/json"),NULL };
HINTERNET hRequest = HttpOpenRequest(hConnectHandle, _T("POST"), GROUP_API_PATH, NULL, NULL, AcceptTypes, 0, 0);
if (hRequest == NULL)
{
InternetCloseHandle(hConnectHandle);
InternetCloseHandle(hOpenHandle);
return false;
}
Step 2 - send the header:
std::wstring HeaderData;
HeaderData += _T("X-WM-CLIENT-ID: ");
HeaderData += _T(CLIENT_ID);
HeaderData += _T("\r\nX-WM-CLIENT-SECRET: ");
HeaderData += _T(CLIENT_SECRET);
HeaderData += _T("\r\n");
HttpAddRequestHeaders(hRequest, HeaderData.c_str(), HeaderData.size(), NULL);
Step 3 - send the message:
std::wstring WJsonData;
WJsonData += _T("{");
WJsonData += _T("\"group_admin\":\"");
WJsonData += groupAdmin;
WJsonData += _T("\",");
WJsonData += _T("\"group_name\":\"");
WJsonData += groupName;
WJsonData += _T("\",");
WJsonData += _T("\"message\":\"");
WJsonData += message;
WJsonData += _T("\"");
WJsonData += _T("}");
const std::string JsonData(WJsonData.begin(), WJsonData.end());
bResults = HttpSendRequest(hRequest, NULL, 0, (LPVOID)(JsonData.c_str()), JsonData.size());
Now just check the result:
TCHAR StatusText[BUFFER_LENGTH] = { 0 };
DWORD StatusTextLen = BUFFER_LENGTH;
HttpQueryInfo(hRequest, HTTP_QUERY_STATUS_TEXT, &StatusText, &StatusTextLen, NULL);
bResults = (StatusTextLen && wcscmp(StatusText, L"OK")==FALSE);

Android Launching Camera Intent from Fragment

I currently have an activity that hosts multiple fragments and I am on my third fragment of a collection.
In that fragment I use an Intent to launch either the Camera or Gallery. See code:
public Intent getImageIntent() {
// Camera.
final List<Intent> cameraIntents = new ArrayList<Intent>();
final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
final PackageManager packageManager = context.getPackageManager();
final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
for (ResolveInfo res : listCam) {
final String packageName = res.activityInfo.packageName;
final Intent intent = new Intent(captureIntent);
intent.setComponent(new ComponentName(res.activityInfo.packageName,
res.activityInfo.name));
intent.setPackage(packageName);
cameraIntents.add(intent);
}
// Filesystem.
final Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
// Chooser of filesystem options.
final Intent chooserIntent = Intent.createChooser(galleryIntent, "Select Source");
// Add the camera options.
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS,
cameraIntents.toArray(new Parcelable[] {}));
// Calling activity should exeecute:
// startActivityForResult(chooserIntent, 1);
return chooserIntent;
}
After that the onActivityResult executes:
private void handleSmallCameraPhoto(Intent intent) {
Bundle extras = intent.getExtras();
mProductBitmap = (Bitmap) extras.get("data");
imgProduct.setImageBitmap(mProductBitmap);
}
Where mProductBitmap is a Bitmap Global Variable and imgProduct is an ImageView already initialized.
For some reason, first: The Camera option force closes the app, and gets a null pointer from the actual fragment itself, like the fragment items are all null again.
Second: The gallery options (More then one) don't error out but don't show the image either.
Any help would be appreciated. I've looked at every response possible, but not many people call an intent from a fragment that isn't the initial fragment that the activity is hosting.
Thanks!
EDIT:
Found out sometimes my Context is Null after the onActivityResult. If anyone has encountered this help is appreciated. Thanks.
EDIT: Below is by onActivityResult method, most of the time the first if should be executed.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (resultCode == Activity.RESULT_OK) {
handleSmallCameraPhoto(intent);
} else {
if (requestCode == 1) {
InputStream stream = null;
if (intent == null) {
System.out.println("DATA IS NULL..");
} else {
try {
if (mProductBitmap != null) {
mProductBitmap.recycle();
}
stream = getActivity().getContentResolver().openInputStream(
intent.getData());
mProductBitmap = BitmapFactory.decodeStream(stream);
System.out.println(mProductBitmap);
System.out.println("Setting image result");
imgProduct.setImageBitmap(mProductBitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (stream != null)
try {
stream.close();
} catch (IOException e2) {
e2.printStackTrace();
}
}
}
}
}
}
Your photo is saved in PATH_TO_SAVE location.
You should in onActivityResult do something like this:
File file = new File(PATH_TO_SAVE);
Bitmap bmp = BitmapFactory.decodeFile(file.getPath());

how to start another application from my application in android

final List<PackageInfo> packs = getPackageManager().getInstalledPackages(0);
The above PackageInfo class for get the list of packages then
get package names for :
ViewHendler hendler = new ViewHendler();
hendler.textLable = (TextView)convertView.findViewById(R.id.textView);
Intent LaunchIntent = getPackageManager().getLaunchIntentForPackage(packageName);
startActivity( LaunchIntent );
then start applicathin using package name call :launchApp(packageName)
void launchApp(String packageName) {
Intent mIntent = getPackageManager().getLaunchIntentForPackage(packageName);
if (mIntent != null) {
try {
startActivity(mIntent);
} catch (ActivityNotFoundException err) {
Toast t = Toast.makeText(getApplicationContext(),
R.string.app_not_found, Toast.LENGTH_SHORT);
t.show();
}
}
}
But didn't get result(start another application from my application).
It's right way to use:
Intent LaunchIntent = getPackageManager().getLaunchIntentForPackage("com.package.name");
startActivity(LaunchIntent);
But probably you have no permission, or you don't have application there.
Firstly check your packageName parameter.

How to dial acces codes after call is started in android?

I am new to android and working on conference manager application .I do not know how to access the dial paid after the call is started in android can someone help me in this case or provide some sample codes for my references.Thank you.This is my call() the first number should be a conference number so i used action call and the second number is a conference pin ,every step will have delay in time
private void call(int profileid) {
ProfileDo profile = adapter.getProfile(profileid);
int stepCount = 0;
long previsouStepDelay=0;
for (StepDO step : profile.getSteps()) {
String url = "tel:" + step.getValue();
stepCount++;
if (stepCount == 1) {
Intent callIntent = null;
callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(url));
startActivity(callIntent);
} else {
try {
Thread.sleep(previsouStepDelay*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Intent callIntent = null;
callIntent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
//callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(callIntent);
}
previsouStepDelay = step.getDelay();
}
}
Can anyone tell me what mistake i did and how can i improvise this?
Use below intent to open dialer screen..
Intent intent = new Intent(Intent.ACTION_DIAL);
startActivity(intent);
reference

Categories