Come aprire Google Play Store direttamente dalla mia applicazione Android?


569

Ho aperto il Google Play Store utilizzando il seguente codice

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);.

Ma mi mostra una Vista azione completa per selezionare l'opzione (browser / Play Store). Devo aprire direttamente l'applicazione nel Play Store.


Risposte:


1437

Puoi farlo usando il market://prefisso .

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

Usiamo un try/catchblocco qui perché Exceptionverrà lanciato se il Play Store non è installato sul dispositivo di destinazione.

NOTA : qualsiasi app può registrarsi come in grado di gestire l' market://details?id=<appId>Uri, se si desidera targetizzare specificamente Google Play, controllare la risposta Berťák


53
se vuoi reindirizzare a tutte le app dello sviluppatore usa market://search?q=pub:"+devNameehttp://play.google.com/store/search?q=pub:"+devName
— Stefano Munarini l'

4
Questa soluzione non funziona se alcune applicazioni utilizzano il filtro intent con lo schema "market: //" definito. Vedi la mia risposta su come aprire Google Play E SOLO l'applicazione Google Play (o browser web se GP non presente). :-)
— Berťák il

18
Per i progetti che utilizzano il sistema di build Gradle, appPackageNameè infatti BuildConfig.APPLICATION_ID. No Context/ Activitydipendenze, riducendo il rischio di perdite di memoria.
— Christian García,

3
Hai ancora bisogno del contesto per avviare l'intento. Context.startActivity ()
— wblaschko il

2
Questa soluzione presuppone che vi sia l'intenzione di aprire un browser Web. Questo non è sempre vero (come su Android TV) quindi fai attenzione. Potresti voler usare intent.resolveActivity (getPackageManager ()) per determinare cosa fare.
— Coda,

161

Molte risposte qui suggeriscono di utilizzare Uri.parse("market://details?id=" + appPackageName)) per aprire Google Play, ma penso che in realtà sia insufficiente :

Alcune applicazioni di terze parti possono utilizzare i propri filtri di intenti con lo "market://"schema definito , quindi possono elaborare Uri fornito anziché Google Play (ho riscontrato questa situazione con l'applicazione ad esempio SnapPea). La domanda è "Come aprire Google Play Store?", Quindi presumo che tu non voglia aprire altre applicazioni. Nota anche che, ad esempio, la valutazione delle app è rilevante solo nell'app GP Store, ecc ...

Per aprire Google Play E SOLO Google Play, utilizzo questo metodo:

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

Il punto è che quando più applicazioni accanto a Google Play possono aprire il nostro intento, la finestra di dialogo di selezione delle app viene saltata e l'app GP viene avviata direttamente.

AGGIORNAMENTO: a volte sembra che apra solo l'app GP, senza aprire il profilo dell'app. Come ha suggerito TrevorWiley nel suo commento, Intent.FLAG_ACTIVITY_CLEAR_TOPpotrebbe risolvere il problema. (Non l'ho ancora provato da solo ...)

Vedi questa risposta per capire cosa Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDEDfa.


4
Anche se questo è buono, sembra anche inaffidabile con l'attuale build di Google Play, se accedete a un'altra pagina di app su Google Play quindi attivate questo codice, si aprirà semplicemente Google Play ma non andrà alla vostra app.
— zoltish

2
@zoltish, ho aggiunto Intent.FLAG_ACTIVITY_CLEAR_TOP alle bandiere e questo sembra risolvere il problema
— TrevorWiley

Ho usato Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED ma non funziona. nessuna nuova istanza aperta nel Play Store
— Praveen Kumar Verma il

3
Cosa succede se usi rateIntent.setPackage("com.android.vending")per assicurarti che l'app PlayStore gestirà questo intento, invece di tutto questo codice?
— dum4ll3,

3
@ dum4ll3 Immagino che tu possa, ma questo codice controlla anche implicitamente se l'app Google Play è installata. Se non lo controlli devi prendere ActivityNotFound
— Daniele Segato il

81

Vai sul link ufficiale dello sviluppatore Android come tutorial passo dopo passo vedi e ottieni il codice per il tuo pacchetto di applicazioni dal Play Store se esiste o le app del Play Store non esistono quindi apri l'applicazione dal browser web.

Link ufficiale per sviluppatori Android

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

Collegamento a una pagina dell'applicazione

Da un sito Web: https://play.google.com/store/apps/details?id=<package_name>

Da un'app Android: market://details?id=<package_name>

Collegamento a un elenco di prodotti

Da un sito Web: https://play.google.com/store/search?q=pub:<publisher_name>

Da un'app Android: market://search?q=pub:<publisher_name>

Collegamento a un risultato della ricerca

Da un sito Web: https://play.google.com/store/search?q=<search_query>&c=apps

Da un'app Android: market://search?q=<seach_query>&c=apps


Utilizzando market: // prefix non è più raccomandato (controlla il link che hai pubblicato)
— Greg Ennis

@GregEnnis dove vedi quel mercato: // prefisso non è più raccomandato?
— loki

@loki Penso che il punto sia che non è più elencato come un suggerimento. Se cerchi quella parola per la parola marketnon troverai alcuna soluzione. Penso che il nuovo modo sia innescare un intento più generico developer.android.com/distribute/marketing-tools/… . Le versioni più recenti dell'app Play Store hanno probabilmente un filtro intento per questo URIhttps://play.google.com/store/apps/details?id=com.example.android
— tir38

25

prova questo

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("market://details?id=com.example.android"));
startActivity(intent);

1
Per sapere come aprire google play in modo indipendente (non incorporato in una nuova vista nella stessa app), controlla la mia risposta.
— code4jhon,

21

Tutte le risposte di cui sopra aprono Google Play in una nuova vista della stessa app, se in realtà vuoi aprire Google Play (o qualsiasi altra app) in modo indipendente:

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

La parte importante è che in realtà apre Google Play o qualsiasi altra app in modo indipendente.

La maggior parte di ciò che ho visto utilizza l'approccio delle altre risposte e non è stato ciò di cui avevo bisogno che questo aiuti qualcuno.

Saluti.


Che cosa è this.cordova? Dove sono le dichiarazioni delle variabili? Dove viene callbackdichiarato e definito?
— Eric

fa parte di un plug-in Cordova, non penso che sia effettivamente rilevante ... hai solo bisogno di un'istanza di PackageManager e avviare un'attività in modo regolare ma questo è il plug-in Cordova di github.com/lampaa che ho sovrascritto qui github.com/code4jhon/org.apache.cordova.startapp
— code4jhon

4
Il mio punto è semplicemente che, questo codice non è in realtà qualcosa che le persone possono semplicemente trasferire sulla propria app per l'uso. Tagliare il grasso e lasciare solo il metodo principale sarebbe utile per i futuri lettori.
— Eric

Sì, ho capito ... per ora sono su app ibride. Non riesco davvero a testare il codice completamente nativo. Ma penso che l'idea sia lì. Se avrò la possibilità, aggiungerò le righe native esatte.
— code4jhon,

spero che questo lo renderà @eric
— code4jhon il

14

Puoi verificare se l' app Google Play Store è installata e, in tal caso, puoi utilizzare il protocollo "market: //" .

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

1
Per sapere come aprire google play in modo indipendente (non incorporato in una nuova vista nella stessa app), controlla la mia risposta.
— code4jhon,

12

Mentre la risposta di Eric è corretta e anche il codice di Berťák funziona. Penso che questo combina entrambi in modo più elegante.

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

Usando setPackage, imponi al dispositivo di utilizzare il Play Store. Se non è installato Play Store, Exceptionverrà catturato.


I documenti ufficiali usano https://play.google.com/store/apps/details?id=invece di market:Come mai? developer.android.com/distribute/marketing-tools/… Ancora una risposta completa e breve.
— serv-inc,

Non ne sono sicuro, ma penso che sia una scorciatoia che Android traduce in " play.google.com/store/apps ". Probabilmente puoi usare anche "market: //" nell'eccezione.
— M3-n50,

11

utilizzare il mercato: //

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + my_packagename));

7

Tu puoi fare:

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

ottenere riferimento qui :

Puoi anche provare l'approccio descritto nella risposta accettata di questa domanda: Impossibile determinare se Google Play Store è installato o meno sul dispositivo Android


Ho già provato con questo codice, questo mostra anche l'opzione per selezionare il browser / Play Store, perché il mio dispositivo ha installato entrambe le app (Google Play Store / Browser).
— Rajesh Kumar,

Per sapere come aprire google play in modo indipendente (non incorporato in una nuova vista nella stessa app), controlla la mia risposta.
— code4jhon,

7

Molto tardi nella festa sono arrivati ​​i documenti ufficiali . E il codice descritto è

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

Mentre configuri questo intento, passa "com.android.vending"in Intent.setPackage()modo che gli utenti vedano i dettagli della tua app nell'app Google Play Store anziché in una selezione . per 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)

Se hai pubblicato un'app istantanea utilizzando Google Play Instant, puoi avviare l'app come segue:

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

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

Penso che questo sia sbagliato, almeno Uri.parse("https://play.google.com/store/apps/details?id=. Su alcuni dispositivi apre il browser Web anziché Play Market.
— CoolMind

Tutto il codice è tratto da documenti ufficiali. Il collegamento è anche allegato nel codice di risposta è descritto qui per un riferimento rapido.
— Husnain Qasim

@CoolMind probabilmente è perché quei dispositivi hanno una versione precedente dell'app Play Store che non ha un filtro di intenti corrispondente a quell'URI.
— tir38

@ tir38, forse è così. Forse non hanno Google Play Services o non sono autorizzati in essi, non ricordo.
— CoolMind

6

Come i documenti ufficiali usano https://invece di market://, questo combina la risposta di Eric e M3-n50 con il riutilizzo del codice (non ripeterti):

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

Cerca di aprirsi con l'app GPlay se esiste e torna ai valori predefiniti.


5

Soluzione pronta all'uso:

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

}

Basato sulla risposta di Eric.


1
Per te funziona? Apre la pagina principale di Google Play, non la pagina della mia app.
— Violet Giraffe

4

Kotlin:

Estensione:

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

Metodo:

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

3

Se desideri aprire Google Play Store dalla tua app, utilizza questo comando direttamente: market://details?gotohome=com.yourAppNameaprirà le pagine del Google Play Store della tua app.

Mostra tutte le app di un editore specifico

Cerca app che utilizzano la query nel titolo o nella descrizione

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


3

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

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

2

La mia funzione di entensione kotlin per questo scopo

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

E nella tua attività

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

2

Ecco il codice finale dalle risposte sopra che tenta per prima cosa di aprire l'app utilizzando l'app Google Play Store e in particolare il Play Store, se non riesce, avvierà la visualizzazione dell'azione utilizzando la versione web: Crediti a @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);
        }
    }

2

Questo link aprirà automaticamente l'app nel market: // se sei su Android e nel browser se sei su PC.

https://play.app.goo.gl/?link=https://play.google.com/store/apps/details?id=com.app.id&ddl=1&pcampaignid=web_ddl_1

Cosa intendi? Hai provato la mia soluzione? Ha funzionato per me.
— Nikolay Shindarov

In realtà nel mio compito, c'è una visualizzazione Web e in visualizzazione Web devo caricare qualsiasi URL. ma in questo caso se è presente un URL playstore mostra il pulsante Apri playstore. quindi devo aprire l'app facendo clic su quel pulsante. sarà dinamico per qualsiasi applicazione, quindi come posso gestirlo?
— hpAndro

Basta provare il linkhttps://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

Ho combinato la risposta di Berkák e Stefano Munarini alla creazione di una soluzione ibrida che gestisce sia lo scenario di valutazione di questa app sia lo scenario Mostra più app .

        /**
         * 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);
            }
        }

uso

  • Per aprire il profilo dei publisher
   @OnClick(R.id.ll_more_apps)
        public void showMoreApps() {
            openPlayStore(true, "Hitesh Sahu");
        }
  • Per aprire la pagina dell'app su PlayStore
@OnClick(R.id.ll_rate_this_app)
public void openAppInPlayStore() {
    openPlayStore(false, "");
}

Id suggerisce di dividere questo codice in metodi più piccoli. È difficile trovare un codice importante in questo spaghetti :) Inoltre stai controllando "com.android.vending" che ne pensi di com.google.market
— Aetherna

1

Popoli, non dimenticate che si potrebbe effettivamente ottenere qualcosa di più da esso. Intendo il monitoraggio UTM per esempio. 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));
}

1

Una versione di kotlin con fallback e sintassi corrente

 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)
    }
}
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.