Sending user to App. If App not exist send to playstore - java

I use this codes to send user to another applications. I wan't the user get send to playstore if the application not exist on he's phone. I was searching for examples but i didn't find anything.
// Launch My App one after clicking the button1
public void launchAppOne(View view) {
Intent launchAppOne= getPackageManager().getLaunchIntentForPackage("com.app.android.myapp1");
startActivity(launchAppOne);
}
// Launch My A after clicking the button2
public void launchAppTwo(View view) {
Intent launchAppTwo = getPackageManager().getLaunchIntentForPackage("com.app.android.myapp2");
startActivity(launchAppTwo);
}

You can use this code. It tries to launch the app and if it doesn't exist, the playstore page for the app is opened.
String packageName = "org.mozilla.firefox";
Intent intent= getPackageManager().getLaunchIntentForPackage(packageName);
if (intent != null){
startActivity(intent);
}else{
try {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + packageName)));
}catch (android.content.ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + packageName)));
}
}

Related

Open a Facebook post URL in android Facebook app programmatically

I'm coding an android - java app which can open a Facebook post url
(ex: https://www.facebook.com/BaHangXom.0/videos/2377836809193490).
I tried some ways to start Facebook app with intent but unsuccessfully.
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("fb://facewebmodal/f?href=" + "https://www.facebook.com/BaHangXom.0/videos/2377836809193490"));
intent.setPackage("com.facebook.katana");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
Could you please give me any idea?
Thank you so much.
Simply open the url:
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/BaHangXom.0/videos/2377836809193490"));
startActivity(intent);
This is the most simple and universal way: user will be able to choose (and remember the choice) whether they want to open the link via main Facebook app, Facebook lite, or the browser.
You can open the facebook app using this code:
public static Intent newFacebookIntent(PackageManager pm, String url) {
Uri uri = Uri.parse(url);
try {
ApplicationInfo applicationInfo = pm.getApplicationInfo("com.facebook.katana", 0);
if (applicationInfo.enabled) {
// http://stackoverflow.com/a/24547437/1048340
uri = Uri.parse("fb://facewebmodal/f?href=" + url);
}
} catch (PackageManager.NameNotFoundException ignored) {
}
return new Intent(Intent.ACTION_VIEW, uri);
}

How to open external links directly in in-app browser (Chrome custom tab) without getting prompt to select the browser

I need to open external links directly in my in-app browser (Chrome custom tab) without getting prompt to select the browser in my android webview app.
Right now if I am clicking on external links in my app then it prompts me and ask me to select any browser (Chrome, Opera, Edge). If I am clicking on chrome then link opens in Chrome custom tab inside the app, but I want that the prompt should not come and link should directly open in Chrome custom tab (like it happens on Instagram, FB, etc.)
/*--- actions based on URL structure ---*/
public boolean url_actions(WebView view, String url){
boolean a = true;
// show toast error if not connected to the network
if (!ASWP_OFFLINE && !DetectConnection.isInternetAvailable(MainActivity.this)) {
Toast.makeText(getApplicationContext(), getString(R.string.check_connection), Toast.LENGTH_SHORT).show();
// use this in a hyperlink to redirect back to default URL :: href="refresh:android"
} else if (url.startsWith("refresh:")) {
String ref_sch = (Uri.parse(url).toString()).replace("refresh:","");
if(ref_sch.matches("URL")){
CURR_URL = ASWV_URL;
}
pull_fresh();
// use this in a hyperlink to launch default phone dialer for specific number :: href="tel:+919876543210"
} else if (url.startsWith("tel:")) {
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
startActivity(intent);
// use this to open your apps page on google play store app :: href="rate:android"
} else if (url.startsWith("rate:")) {
final String app_package = getPackageName(); //requesting app package name from Context or Activity object
try {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + app_package)));
} catch (ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + app_package)));
}
// sharing content from your webview to external apps :: href="share:URL" and remember to place the URL you want to share after share:___
} else if (url.startsWith("share:")) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, view.getTitle());
intent.putExtra(Intent.EXTRA_TEXT, view.getTitle()+"\nVisit: "+(Uri.parse(url).toString()).replace("share:",""));
startActivity(Intent.createChooser(intent, getString(R.string.share_w_friends)));
// use this in a hyperlink to exit your app :: href="exit:android"
} else if (url.startsWith("exit:")) {
aswm_exit();
// getting location for offline files
} else if (url.startsWith("offloc:")) {
String offloc = ASWV_URL+"?loc="+get_location();
aswm_view(offloc,false, asw_error_counter);
Log.d("OFFLINE LOC REQ",offloc);
// creating firebase notification for offline files
} else if (url.startsWith("fcm:")) {
String fcm = ASWV_URL+"?fcm="+fcm_token();
aswm_view(fcm,false, asw_error_counter);
Log.d("OFFLINE_FCM_TOKEN",fcm);
// opening external URLs in android default web browser
} else if (ASWP_EXTURL && !aswm_host(url).equals(ASWV_HOST) && !url.contains("oauth")) {
aswm_view(url,true, asw_error_counter);
// else return false for no special action
} else {
a = false;
}
return a;
}
//Opening URLs inside webview with request
void aswm_view(String url, Boolean tab, int error_counter) {
if(error_counter > 2){
asw_error_counter = 0;
aswm_exit();
}else {
if(tab){
if(ASWP_TAB) {
CustomTabsIntent.Builder intentBuilder = new CustomTabsIntent.Builder();
intentBuilder.setToolbarColor(ContextCompat.getColor(this, R.color.colorPrimary));
intentBuilder.setSecondaryToolbarColor(ContextCompat.getColor(this, R.color.colorPrimaryDark));
intentBuilder.setStartAnimations(this, android.R.anim.slide_in_left, android.R.anim.slide_out_right);
intentBuilder.setExitAnimations(this, android.R.anim.slide_in_left, android.R.anim.slide_out_right);
CustomTabsIntent customTabsIntent = intentBuilder.build();
try {
customTabsIntent.launchUrl(MainActivity.this, Uri.parse(url));
} catch (ActivityNotFoundException e) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
}
}else{
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
}
} else {
if (url.contains("?")) { // check to see whether the url already has query parameters and handle appropriately.
url += "&";
} else {
url += "?";
}
url += "rid=" + random_id();
asw_view.loadUrl(url);
}
}
}
If I am entering False in "aswm_view(url,true, asw_error_counter);" then the external links open in webview which I don't want to happen.
Thanks in advance, and if required I can share more code.
EDIT: I have added the aswm_view method as per the request
By Viewing your aswm_view method, either ASWP_TAB is going false or MainActivity is not found.
Please check both carefully in aswm_view method.

A link not to the mobile broswer, but to the applications

I have a link to some page (Instagram), when I click on the link, it takes me to the link and the username to that like in the mobile browser, what should I type in order to work it in Instagram application in the mobile? If it doesn't exist, it will go to play.google/instagram in the play store
This is the link but it's not what I want
blah.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.instagram.com/blahhhh"));
startActivity(browserIntent);
}
});
try {
Intent LaunchIntent =
getPackageManager().getLaunchIntentForPackage("com.instagram.android");
startActivity(LaunchIntent);
//Here you can add more information, such as the specific profile that you want to launch, in Intent format
}
catch (Exception myIntent) {
//TODO Auto-generated catch block
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=com.instagram.android"));
startActivity(browserIntent);
}

How to get the user authentication in Splash Activity

I'm working on a small app that has a Splash Screen and a User Login.
I want to launch different tab menu based on the user's ID.
Let say I have an Admin who has ID == "100" will get AdminTabActivity and rest of others will get UserTabActivity. so I wrote it like this. I'm simply passing the user ID from here to the MainActivity.
SplashActivity.java
public void run(){
try{
sleep(1000);
Intent in = new Intent(getApplicationContext(), MainActivity.class);
startActivity(in);
finish();
} catch (InterruptedException e){
e.printStackTrace();
}finally {
}
}
LoginActivity.java
//Stores and Grabs the user ID from sqlite db
db.addUser(json_user.getString(KEY_ID),
json_user.getString(KEY_NAME));
Intent i = new Intent(getApplicationContext(), MainActivity.class);
i.putExtra(KEY_ID, id);
startActivity(i);
finish();
MainActivity.java
Intent i = getIntent();
String id = i.getStringExtra(KEY_ID);
if("001".equals(id)){
/* Launch Admin Screen if ID == 100 */
Intent in = new Intent(getApplicationContext(), AdminTabActivity.class);
startActivity(in);
finish();
}else{
/* Launch User Screen if ID !== 100 */
Intent in = new Intent(getApplicationContext(), UserTabActivity.class);
startActivity(in);
finish();
}
If the user exits out of the app and returns back, it will skips the LoginActivity and go straight from Splash to MainActivity (which I want it to be), but the if block will skip this time even if the user has the ID == "100". Hope it makes sense, if not please kindly let me know so I can explain more. Thank you!

How to launch an Activity from another Application in Android

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)
}

Categories