620

I have open the Google Play store using the following code

Intent i = new Intent(android.content.Intent.ACTION_VIEW);
i.setData(Uri.parse("https://play.google.com/store/apps/details?id=my packagename "));
startActivity(i);.

But it shows me a Complete Action View as to select the option (browser/play store). I need to open the application in Play Store directly.

lmark
  • 45
  • 7
Rajesh Kumar
  • 6,238
  • 3
  • 13
  • 14
  • Does this answer your question? ["Rate This App"-link in Google Play store app on the phone](https://stackoverflow.com/questions/10816757/rate-this-app-link-in-google-play-store-app-on-the-phone) – Yoav Feuerstein May 25 '20 at 14:20

23 Answers23

1557

You can do this using the market:// prefix.

Java

final String appPackageName = getPackageName(); // getPackageName() from Context or Activity object
try {
    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));
} catch (android.content.ActivityNotFoundException anfe) {
    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackageName)));
}

Kotlin

try {
    startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=$packageName")))
} catch (e: ActivityNotFoundException) {
    startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=$packageName")))
}

We use a try/catch block here because an Exception will be thrown if the Play Store is not installed on the target device.

NOTE: any app can register as capable of handling the market://details?id=<appId> Uri, if you want to specifically target Google Play check the Berťák answer

Eric
  • 63,873
  • 22
  • 120
  • 135
  • I have tried already with this code, this is also shows the option to select the browser/play store, because my device have installed both apps(google play store/browser). – Rajesh Kumar Aug 01 '12 at 05:46
  • Not sure what to tell you. I use this code on both 2.3.3 and 4.1 and both open up the Play Store. Additionally, [the docs](http://developer.android.com/distribute/googleplay/promote/linking.html#android-app) say `market://` "*Launches the Play Store app*". – Eric Aug 01 '12 at 05:51
  • 60
    if you want to redirect to all Developer's apps use `market://search?q=pub:"+devName` and `http://play.google.com/store/search?q=pub:"+devName` – Stefano Munarini Aug 11 '13 at 13:18
  • thank u for the post. Me also tried with this code but it shows the option to select the browser/playstore. rajesh if u got the answer for this issue means update the post. – Nathiya Sep 04 '13 at 11:14
  • For how to open google play independently (not embedded in a new view in the same app) please check my answer. – code4jhon Jul 29 '14 at 03:12
  • What if I want to open Play with a 'referrer' param? Am I expected to simply add it to the URI, e.g. "market://xxxxx&referrer=abc" ? Or do I need to update some other part of the Intent/action/etc? – Sagi Mann Oct 30 '14 at 11:57
  • @SagiMann-TROPHiT Honestly, I'm not sure. You'd be better off starting a new question. – Eric Oct 31 '14 at 02:17
  • Doesn't the web link need https now? – ooolala Dec 28 '14 at 06:29
  • @ooolala Need, no. Should have, yes. Will change that. – Eric Dec 28 '14 at 20:09
  • Can I return to my app after the download is finish? Thanks. – offset Jan 15 '15 at 10:56
  • @offset No, unfortunately not. There might be an `Intent` you could capture on package addition, but even then I don't think the OS provides you the control to switch over to your app. (Just to do something in the background.) – Eric Jan 15 '15 at 16:19
  • 4
    This solution does not work, if some application uses intent filter with "market://" scheme defined. See my answer how to open Google Play AND ONLY Google Play application (or webbrowser if GP not present). :-) – Berťák Jan 22 '15 at 14:18
  • 21
    For projects using the Gradle build system, `appPackageName` is in fact `BuildConfig.APPLICATION_ID`. No `Context`/`Activity` dependencies, reducing the risk of memory leaks. – Christian García Aug 10 '15 at 15:42
  • 3
    You still need the context to launch the intent. Context.startActivity() – wblaschko Dec 07 '15 at 22:32
  • 2
    This solution assumes there is an intent to open a web browser. This isn't always true (like on Android TV) so be cautious. You may want to use intent.resolveActivity(getPackageManager()) to determine what to do. – Coda Aug 04 '16 at 05:56
  • Developer is now: From a website: http://play.google.com/store/dev?id= From an Android app: market://dev?id= – MPaulo Mar 27 '17 at 04:10
  • 1
    market:// is not working if i am redirecting from another domain url. For example if user is opening url https://www.example.com/blabla in his browser and i am simply redirecting to market://details?id=com.example.blabla previously its working but from 1 week onwards its not working. can anyone help me regarding this. i am using nodejs for URL redirection. – Dhaval Rajani Feb 08 '18 at 10:02
  • @DhavalRajani It wouldn't work on my emulator but on real hardware for me. – Bostrot Jun 23 '18 at 21:34
  • I think you should use application id instead of package name. – Ashwin Oct 14 '18 at 09:05
174

Many answers here suggest to use Uri.parse("market://details?id=" + appPackageName)) to open Google Play, but I think it is insufficient in fact:

Some third-party applications can use its own intent-filters with "market://" scheme defined, thus they can process supplied Uri instead of Google Play (I experienced this situation with e.g.SnapPea application). The question is "How to open the Google Play Store?", so I assume, that you do not want to open any other application. Please also note, that e.g. app rating is only relevant in GP Store app etc...

To open Google Play AND ONLY Google Play I use this method:

public static void openAppRating(Context context) {
    // you can also use BuildConfig.APPLICATION_ID
    String appId = context.getPackageName();
    Intent rateIntent = new Intent(Intent.ACTION_VIEW,
        Uri.parse("market://details?id=" + appId));
    boolean marketFound = false;

    // find all applications able to handle our rateIntent
    final List<ResolveInfo> otherApps = context.getPackageManager()
        .queryIntentActivities(rateIntent, 0);
    for (ResolveInfo otherApp: otherApps) {
        // look for Google Play application
        if (otherApp.activityInfo.applicationInfo.packageName
                .equals("com.android.vending")) {

            ActivityInfo otherAppActivity = otherApp.activityInfo;
            ComponentName componentName = new ComponentName(
                    otherAppActivity.applicationInfo.packageName,
                    otherAppActivity.name
                    );
            // make sure it does NOT open in the stack of your activity
            rateIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            // task reparenting if needed
            rateIntent.addFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
            // if the Google Play was already open in a search result
            //  this make sure it still go to the app page you requested
            rateIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            // this make sure only the Google Play app is allowed to
            // intercept the intent
            rateIntent.setComponent(componentName);
            context.startActivity(rateIntent);
            marketFound = true;
            break;

        }
    }

    // if GP not present on device, open web browser
    if (!marketFound) {
        Intent webIntent = new Intent(Intent.ACTION_VIEW,
            Uri.parse("https://play.google.com/store/apps/details?id="+appId));
        context.startActivity(webIntent);
    }
}

The point is that when more applications beside Google Play can open our intent, app-chooser dialog is skipped and GP app is started directly.

UPDATE: Sometimes it seems that it opens GP app only, without opening the app's profile. As TrevorWiley suggested in his comment, Intent.FLAG_ACTIVITY_CLEAR_TOP could fix the problem. (I didn't test it myself yet...)

See this answer for understanding what Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED does.

Community
  • 1
  • 1
Berťák
  • 6,819
  • 2
  • 26
  • 37
  • 4
    While this is good it also seems unreliable with the current Google Play build, if you enter another apps page on Google Play then trigger this code, it will just open Google Play but not go to your app. – zoltish Dec 28 '15 at 08:28
  • 2
    @zoltish, I've added Intent.FLAG_ACTIVITY_CLEAR_TOP to the flags and that seems to fix the problem – TrevorWiley May 25 '16 at 13:55
  • I have used Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED but not work. no any new Instance open of Play store – Praveen Kumar Verma Aug 23 '16 at 13:40
  • 3
    What happens if you use `rateIntent.setPackage("com.android.vending")` to be sure the PlayStore app gonna handle this intent, Instead of all this code? – dum4ll3 Sep 21 '16 at 19:37
  • 3
    @dum4ll3 I guess you can but this code also implicitly check if the Google Play app is installed. If you do not check it you need to catch for ActivityNotFound – Daniele Segato Dec 23 '16 at 11:05
  • You can use `getLaunchIntentForPackage("com.android.vending")` instead of the first `for` `if`. – Dr.jacky Dec 04 '19 at 08:53
87

Go on Android Developer official link as tutorial step by step see and got the code for your application package from play store if exists or play store apps not exists then open application from web browser.

Android Developer official link

https://developer.android.com/distribute/tools/promote/linking.html

Linking to a Application Page

From a web site: https://play.google.com/store/apps/details?id=<package_name>

From an Android app: market://details?id=<package_name>

Linking to a Product List

From a web site: https://play.google.com/store/search?q=pub:<publisher_name>

From an Android app: market://search?q=pub:<publisher_name>

Linking to a Search Result

From a web site: https://play.google.com/store/search?q=<search_query>&c=apps

From an Android app: market://search?q=<seach_query>&c=apps

NAP Developer
  • 3,353
  • 1
  • 21
  • 35
  • Using market:// prefix is not recommended anymore (check the link you posted) – Greg Ennis Mar 14 '19 at 15:23
  • @GregEnnis where you see that market:// prefix is not recommended anymore ? – zeus Feb 01 '20 at 11:43
  • 2
    @loki I think the point is that it's not listed as a suggestion any more. If you search that page for the word `market` you won't find any solution. I think the new way is to fire off a more generic intent https://developer.android.com/distribute/marketing-tools/linking-to-google-play#android-app . More recent versions of the Play Store app probably have an intent filter for this URI `https://play.google.com/store/apps/details?id=com.example.android` – tir38 Mar 23 '20 at 18:17
26

try this

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("market://details?id=com.example.android"));
startActivity(intent);
Youddh
  • 1,496
  • 4
  • 34
  • 51
  • 1
    For how to open google play independently (not embedded in a new view in the same app) please check my answer. – code4jhon Jul 29 '14 at 03:14
23

All of the above answers open Google Play in a new view of the same app, if you actually want to open Google Play (or any other app) independently:

Intent launchIntent = getPackageManager().getLaunchIntentForPackage("com.android.vending");

// package name and activity
ComponentName comp = new ComponentName("com.android.vending",
                                       "com.google.android.finsky.activities.LaunchUrlHandlerActivity"); 
launchIntent.setComponent(comp);

// sample to open facebook app
launchIntent.setData(Uri.parse("market://details?id=com.facebook.katana"));
startActivity(launchIntent);

The important part is that actually opens google play or any other app independently.

Most of what I have seen uses the approach of the other answers and it was not what I needed hopefully this helps somebody.

Regards.

ישו אוהב אותך
  • 22,515
  • 9
  • 59
  • 80
code4jhon
  • 4,785
  • 8
  • 36
  • 54
  • What is `this.cordova`? Where are the variable declarations? Where is `callback` declared and defined? – Eric Jul 29 '14 at 04:15
  • this is part of a Cordova plugin, I don't think that is actually relevant ... you just need an instance of PackageManager and start an activity in a regular way but this is the cordova plugin of https://github.com/lampaa which I overwrote here https://github.com/code4jhon/org.apache.cordova.startapp – code4jhon Jul 29 '14 at 04:33
  • 4
    My point is simply that, this code isn't really something that people can simply port to their own app for use. Trimming the fat and leaving just the core method would be useful to future readers. – Eric Jul 29 '14 at 05:04
  • Yes, I understand ... for now I am on hybrid apps. Can't really test completely native code. But I think the idea is there. If I have a chance I will add exact native lines. – code4jhon Jul 29 '14 at 05:18
  • hopefully this will make it @eric – code4jhon Jul 29 '14 at 05:30
21

While Eric's answer is correct and Berťák's code also works. I think this combines both more elegantly.

try {
    Intent appStoreIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName));
    appStoreIntent.setPackage("com.android.vending");

    startActivity(appStoreIntent);
} catch (android.content.ActivityNotFoundException exception) {
    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackageName)));
}

By using setPackage, you force the device to use the Play Store. If there is no Play Store installed, the Exception will be caught.

M3-n50
  • 554
  • 1
  • 7
  • 19
  • The official docs use `https://play.google.com/store/apps/details?id=` instead of `market:` How come? https://developer.android.com/distribute/marketing-tools/linking-to-google-play#android-app Still a comprehensive and short answer. – serv-inc Jun 25 '19 at 06:28
  • I tried Berťák's code and it works but this one is much simpler. – kuchi May 08 '21 at 07:07
15

You can check if the Google Play Store app is installed and, if this is the case, you can use the "market://" protocol.

final String my_package_name = "........."  // <- HERE YOUR PACKAGE NAME!!
String url = "";

try {
    //Check whether Google Play store is installed or not:
    this.getPackageManager().getPackageInfo("com.android.vending", 0);

    url = "market://details?id=" + my_package_name;
} catch ( final Exception e ) {
    url = "https://play.google.com/store/apps/details?id=" + my_package_name;
}


//Open the app page in Google Play store:
final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
startActivity(intent);
Paolo Rovelli
  • 8,082
  • 1
  • 52
  • 37
  • 1
    For how to open google play independently (not embedded in a new view in the same app) please check my answer. – code4jhon Jul 29 '14 at 03:13
12

use market://

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + my_packagename));
MBH
  • 15,020
  • 18
  • 91
  • 140
Johannes Staehlin
  • 3,550
  • 7
  • 32
  • 50
7

You can do:

final Uri marketUri = Uri.parse("market://details?id=" + packageName);
startActivity(new Intent(Intent.ACTION_VIEW, marketUri));

get Reference here:

You can also try the approach described in the accepted answer of this question: Cannot determine whether Google play store is installed or not on Android device

Community
  • 1
  • 1
almalkawi
  • 1,098
  • 1
  • 10
  • 17
  • I have tried already with this code, this is also shows the option to select the browser/play store, because my device have installed both apps(google play store/browser). – Rajesh Kumar Aug 01 '12 at 05:45
  • For how to open google play independently (not embedded in a new view in the same app) please check my answer. – code4jhon Jul 29 '14 at 03:13
7

As the official docs use https:// instead of market://, this combines Eric's and M3-n50's answer with code reuse (don't repeat yourself):

Intent intent = new Intent(Intent.ACTION_VIEW)
    .setData(Uri.parse("https://play.google.com/store/apps/details?id=" + getPackageName()));
try {
    startActivity(new Intent(intent)
                  .setPackage("com.android.vending"));
} catch (android.content.ActivityNotFoundException exception) {
    startActivity(intent);
}

It tries to open with the GPlay app if it exists and falls back to default.

serv-inc
  • 29,557
  • 9
  • 128
  • 146
7

Kotlin:

Extension:

fun Activity.openAppInGooglePlay(){

val appId = BuildConfig.APPLICATION_ID
try {
    this.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=$appId")))
} catch (anfe: ActivityNotFoundException) {
    this.startActivity(
        Intent(
            Intent.ACTION_VIEW,
            Uri.parse("https://play.google.com/store/apps/details?id=$appId")
        )
    )
}}

Method:

    fun openAppInGooglePlay(activity:Activity){

        val appId = BuildConfig.APPLICATION_ID
        try {
            activity.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=$appId")))
        } catch (anfe: ActivityNotFoundException) {
            activity.startActivity(
                Intent(
                    Intent.ACTION_VIEW,
                    Uri.parse("https://play.google.com/store/apps/details?id=$appId")
                )
            )
        }
    }
Danielvgftv
  • 369
  • 5
  • 4
6

Ready-to-use solution:

public class GoogleServicesUtils {

    public static void openAppInGooglePlay(Context context) {
        final String appPackageName = context.getPackageName();
        try {
            context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));
        } catch (android.content.ActivityNotFoundException e) { // if there is no Google Play on device
            context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackageName)));
        }
    }

}

Based on Eric's answer.

Alexandr
  • 3,429
  • 3
  • 27
  • 50
6

Very late in the party Official docs are here. And code described is

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(
    "https://play.google.com/store/apps/details?id=com.example.android"));
intent.setPackage("com.android.vending");
startActivity(intent);

As you configure this intent, pass "com.android.vending" into Intent.setPackage() so that users see your app's details in the Google Play Store app instead of a chooser. for KOTLIN

val intent = Intent(Intent.ACTION_VIEW).apply {
    data = Uri.parse(
            "https://play.google.com/store/apps/details?id=com.example.android")
    setPackage("com.android.vending")
}
startActivity(intent)

If you have published an instant app using Google Play Instant, you can launch the app as follows:

Intent intent = new Intent(Intent.ACTION_VIEW);
Uri.Builder uriBuilder = Uri.parse("https://play.google.com/store/apps/details")
    .buildUpon()
    .appendQueryParameter("id", "com.example.android")
    .appendQueryParameter("launch", "true");

// Optional parameters, such as referrer, are passed onto the launched
// instant app. You can retrieve these parameters using
// Activity.getIntent().getData().
uriBuilder.appendQueryParameter("referrer", "exampleCampaignId");

intent.setData(uriBuilder.build());
intent.setPackage("com.android.vending");
startActivity(intent);

For KOTLIN

val uriBuilder = Uri.parse("https://play.google.com/store/apps/details")
        .buildUpon()
        .appendQueryParameter("id", "com.example.android")
        .appendQueryParameter("launch", "true")

// Optional parameters, such as referrer, are passed onto the launched
// instant app. You can retrieve these parameters using Activity.intent.data.
uriBuilder.appendQueryParameter("referrer", "exampleCampaignId")

val intent = Intent(Intent.ACTION_VIEW).apply {
    data = uriBuilder.build()
    setPackage("com.android.vending")
}
startActivity(intent)
Husnain Qasim
  • 169
  • 2
  • 6
  • I think, this is wrong, at least, `Uri.parse("https://play.google.com/store/apps/details?id=`. On some devices it opens web-browser instead of Play Market. – CoolMind Feb 02 '19 at 12:18
  • All the code is taken from official docs. Link is also attached in answer code is described here for a quick reference. – Husnain Qasim Feb 07 '19 at 19:05
  • @CoolMind the reason for that is probably because those devices have an older version of Play Store app which don't have an intent filter matching that URI. – tir38 Mar 23 '20 at 18:19
  • @tir38, maybe so. Maybe they don't have Google Play Services or not authorized in them, I don't remember. – CoolMind Mar 23 '20 at 18:49
5

This link will open the app automatically in market:// if you are on Android and in browser if you are on PC.

https://play.app.goo.gl/?link=https://play.google.com/store/apps/details?id=com.app.id&ddl=1&pcampaignid=web_ddl_1
Nikolay Shindarov
  • 1,051
  • 2
  • 9
  • 20
  • Actually in my task, there is an webview and in webview I have to load any URL. but in that if there is open any playstore url it shows open playstore button. so I need to open app on click of that button. it will be dynamic for any application, so how can I manage? – hpAndro Mar 18 '19 at 12:31
  • Just try the link ```https://play.app.goo.gl/?link=https://play.google.com/store/apps/details?id=com.app.id&ddl=1&pcampaignid=web_ddl_1 ``` – Nikolay Shindarov Mar 18 '19 at 13:38
5

Kotlin

fun openAppInPlayStore(appPackageName: String) {
    try {
        startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=$appPackageName")))
    } catch (exception: android.content.ActivityNotFoundException) {
        startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=$appPackageName")))
    }
}
Community
  • 1
  • 1
Khemraj Sharma
  • 46,529
  • 18
  • 168
  • 182
5

Some of the answers to this question are outdated.

What worked for me (in 2020) was to explicitly tell the intent to skip the chooser and directly open the play store app, according to this link:

"If you want to link to your products from an Android app, create an Intent that opens a URL. As you configure this intent, pass "com.android.vending" into Intent.setPackage() so that users see your app's details in the Google Play Store app instead of a chooser."

This is the Kotlin code I used to direct users to viewing the app containing the package name com.google.android.apps.maps in Google Play:

val intent = Intent(Intent.ACTION_VIEW).apply {
               data = Uri.parse("http://play.google.com/store/apps/details?id=com.google.android.apps.maps")
               setPackage("com.android.vending")
            }
            startActivity(intent)

I hope that helps someone!

appoll
  • 2,496
  • 25
  • 37
4

If you want to open Google Play store from your app then use this command directy: market://details?gotohome=com.yourAppName, it will open your app's Google Play store pages.

Show all apps by a specific publisher

Search for apps that using the Query on its title or description

Reference: https://tricklio.com/market-details-gotohome-1/

JJD
  • 44,755
  • 49
  • 183
  • 309
Tahmid
  • 315
  • 2
  • 9
3

Here is the final code from the answers above that first attempts to open the app using the Google play store app and specifically play store, if it fails, it will start the action view using the web version: Credits to @Eric, @Jonathan Caballero

public void goToPlayStore() {
        String playStoreMarketUrl = "market://details?id=";
        String playStoreWebUrl = "https://play.google.com/store/apps/details?id=";
        String packageName = getActivity().getPackageName();
        try {
            Intent intent =  getActivity()
                            .getPackageManager()
                            .getLaunchIntentForPackage("com.android.vending");
            if (intent != null) {
                ComponentName androidComponent = new ComponentName("com.android.vending",
                        "com.google.android.finsky.activities.LaunchUrlHandlerActivity");
                intent.setComponent(androidComponent);
                intent.setData(Uri.parse(playStoreMarketUrl + packageName));
            } else {
                intent = new Intent(Intent.ACTION_VIEW, Uri.parse(playStoreMarketUrl + packageName));
            }
            startActivity(intent);
        } catch (ActivityNotFoundException e) {
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(playStoreWebUrl + packageName));
            startActivity(intent);
        }
    }
MoGa
  • 627
  • 6
  • 14
2
public void launchPlayStore(Context context, String packageName) {
    Intent 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)));
        }
    }
Sharath kumar
  • 3,864
  • 1
  • 10
  • 20
2

My kotlin entension function for this purpose

fun Context.canPerformIntent(intent: Intent): Boolean {
        val mgr = this.packageManager
        val list = mgr.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY)
        return list.size > 0
    }

And in your activity

val uri = if (canPerformIntent(Intent(Intent.ACTION_VIEW, Uri.parse("market://")))) {
            Uri.parse("market://details?id=" + appPackageName)
        } else {
            Uri.parse("https://play.google.com/store/apps/details?id=" + appPackageName)
        }
        startActivity(Intent(Intent.ACTION_VIEW, uri))
Arpan Sarkar
  • 1,749
  • 2
  • 10
  • 20
1

I have combined both Berťák and Stefano Munarini answer to creating a hybrid solution which handles both Rate this App and Show More App scenario.

        /**
         * This method checks if GooglePlay is installed or not on the device and accordingly handle
         * Intents to view for rate App or Publisher's Profile
         *
         * @param showPublisherProfile pass true if you want to open Publisher Page else pass false to open APp page
         * @param publisherID          pass Dev ID if you have passed PublisherProfile true
         */
        public void openPlayStore(boolean showPublisherProfile, String publisherID) {

            //Error Handling
            if (publisherID == null || !publisherID.isEmpty()) {
                publisherID = "";
                //Log and continue
                Log.w("openPlayStore Method", "publisherID is invalid");
            }

            Intent openPlayStoreIntent;
            boolean isGooglePlayInstalled = false;

            if (showPublisherProfile) {
                //Open Publishers Profile on PlayStore
                openPlayStoreIntent = new Intent(Intent.ACTION_VIEW,
                        Uri.parse("market://search?q=pub:" + publisherID));
            } else {
                //Open this App on PlayStore
                openPlayStoreIntent = new Intent(Intent.ACTION_VIEW,
                        Uri.parse("market://details?id=" + getPackageName()));
            }

            // find all applications who can handle openPlayStoreIntent
            final List<ResolveInfo> otherApps = getPackageManager()
                    .queryIntentActivities(openPlayStoreIntent, 0);
            for (ResolveInfo otherApp : otherApps) {

                // look for Google Play application
                if (otherApp.activityInfo.applicationInfo.packageName.equals("com.android.vending")) {

                    ActivityInfo otherAppActivity = otherApp.activityInfo;
                    ComponentName componentName = new ComponentName(
                            otherAppActivity.applicationInfo.packageName,
                            otherAppActivity.name
                    );
                    // make sure it does NOT open in the stack of your activity
                    openPlayStoreIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    // task reparenting if needed
                    openPlayStoreIntent.addFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
                    // if the Google Play was already open in a search result
                    //  this make sure it still go to the app page you requested
                    openPlayStoreIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    // this make sure only the Google Play app is allowed to
                    // intercept the intent
                    openPlayStoreIntent.setComponent(componentName);
                    startActivity(openPlayStoreIntent);
                    isGooglePlayInstalled = true;
                    break;

                }
            }
            // if Google Play is not Installed on the device, open web browser
            if (!isGooglePlayInstalled) {

                Intent webIntent;
                if (showPublisherProfile) {
                    //Open Publishers Profile on web browser
                    webIntent = new Intent(Intent.ACTION_VIEW,
                            Uri.parse("http://play.google.com/store/search?q=pub:" + getPackageName()));
                } else {
                    //Open this App on web browser
                    webIntent = new Intent(Intent.ACTION_VIEW,
                            Uri.parse("https://play.google.com/store/apps/details?id=" + getPackageName()));
                }
                startActivity(webIntent);
            }
        }

Usage

  • To Open Publishers Profile
   @OnClick(R.id.ll_more_apps)
        public void showMoreApps() {
            openPlayStore(true, "Hitesh Sahu");
        }
  • To Open App Page on PlayStore
@OnClick(R.id.ll_rate_this_app)
public void openAppInPlayStore() {
    openPlayStore(false, "");
}
Hitesh Sahu
  • 31,496
  • 11
  • 150
  • 116
  • Id suggest divide this code into smaller methods. It's hard to find important code in this spaghetti :) Plus you're checking for _"com.android.vending"_ what about _com.google.market_ – Aetherna Jan 03 '18 at 16:45
1

Peoples, dont forget that you could actually get something more from it. I mean UTM tracking for example. https://developers.google.com/analytics/devguides/collection/android/v4/campaigns

public static final String MODULE_ICON_PACK_FREE = "com.example.iconpack_free";
public static final String APP_STORE_URI =
        "market://details?id=%s&referrer=utm_source=%s&utm_medium=app&utm_campaign=plugin";
public static final String APP_STORE_GENERIC_URI =
        "https://play.google.com/store/apps/details?id=%s&referrer=utm_source=%s&utm_medium=app&utm_campaign=plugin";

try {
    startActivity(new Intent(
        Intent.ACTION_VIEW,
        Uri.parse(String.format(Locale.US,
            APP_STORE_URI,
            MODULE_ICON_PACK_FREE,
            getPackageName()))).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
} catch (android.content.ActivityNotFoundException anfe) {
    startActivity(new Intent(
        Intent.ACTION_VIEW,
        Uri.parse(String.format(Locale.US,
            APP_STORE_GENERIC_URI,
            MODULE_ICON_PACK_FREE,
            getPackageName()))).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
}
Alex
  • 732
  • 9
  • 11
1

A kotlin verison with fallback and current syntax

 fun openAppInPlayStore() {
    val uri = Uri.parse("market://details?id=" + context.packageName)
    val goToMarketIntent = Intent(Intent.ACTION_VIEW, uri)

    var flags = Intent.FLAG_ACTIVITY_NO_HISTORY or Intent.FLAG_ACTIVITY_MULTIPLE_TASK or Intent.FLAG_ACTIVITY_NEW_TASK
    flags = if (Build.VERSION.SDK_INT >= 21) {
        flags or Intent.FLAG_ACTIVITY_NEW_DOCUMENT
    } else {
        flags or Intent.FLAG_ACTIVITY_CLEAR_TASK
    }

    goToMarketIntent.addFlags(flags)

    try {
        startActivity(context, goToMarketIntent, null)
    } catch (e: ActivityNotFoundException) {
        val intent = Intent(Intent.ACTION_VIEW,
                Uri.parse("http://play.google.com/store/apps/details?id=" + context.packageName))

        startActivity(context, intent, null)
    }
}
kuzdu
  • 5,943
  • 1
  • 37
  • 56