Enlace "Calificar esta aplicación" en la aplicación Google Play Store en el teléfono

266

Me gustaría poner un enlace "Calificar esta aplicación" en una aplicación de Android para abrir la lista de aplicaciones en la aplicación de la tienda Google Play del usuario en su teléfono.

  1. ¿Qué código tengo que escribir para crear el market:// o http://-link abierto en la aplicación de la tienda Google Play en el teléfono?
  2. ¿Dónde pones el código?
  3. ¿Alguien tiene una implementación de muestra de esto?
  4. ¿Tiene que especificar la pantalla donde se colocará el enlace market://o http://cuál es el mejor para usar market://o http://?
Adreno
fuente
Esto tiene todo lo que necesita: github.com/delight-im/AppRater Y puede buscar el código fuente para comprender cómo se hace.
caw

Respuestas:

555

Abro Play Store desde mi aplicación con el siguiente código:

    Uri uri = Uri.parse("market://details?id=" + context.getPackageName());
    Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
    // To count with Play market backstack, After pressing back button, 
    // to taken back to our application, we need to add following flags to intent. 
    goToMarket.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY |
                    Intent.FLAG_ACTIVITY_NEW_DOCUMENT |
                    Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
    try {
        startActivity(goToMarket);
    } catch (ActivityNotFoundException e) {
        startActivity(new Intent(Intent.ACTION_VIEW,
                Uri.parse("http://play.google.com/store/apps/details?id=" + context.getPackageName())));
    }

Esto abrirá Play Store con la página de tu aplicación ya abierta. El usuario puede calificarlo allí.

miguel.rodelas
fuente
2
¿Dónde en el androidmanifest.xml coloco este código? ¿Necesito agregar algo más? ¿Cómo corresponde eso a un enlace o botón real en una pantalla que el usuario presiona? Gracias
Adreno
1
No necesita agregar ningún código al manifiesto. Solo tiene que colocar este código dentro de OnClickListener de su botón / enlace, de modo que cuando se hace clic en el botón, se ejecuta el código y se inicia Play Store.
miguel.rodelas
61
Esta solución no cuenta con el backstack de Play market. Después de presionar el botón Atrás, no volverá a su aplicación. Si lo desea, agregue esta línea: intent.addFlags (Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
Jan Muller
24
Intención.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET: Esta constante ha quedado en desuso en el nivel 21 de API. A partir de la API 21, esto funciona de manera idéntica a FLAG_ACTIVITY_NEW_DOCUMENT que debería usarse en lugar de esto.
xnagyg
1
Si llama desde una clase Java que no es de actividad, debe pasar el contexto como context.startActivity (goToMarket);
DMur
47

Aquí hay un código que funciona y actualizado :)

/*
* Start with rating the app
* Determine if the Play Store is installed on the device
*
* */
public void rateApp()
{
    try
    {
        Intent rateIntent = rateIntentForUrl("market://details");
        startActivity(rateIntent);
    }
    catch (ActivityNotFoundException e)
    {
        Intent rateIntent = rateIntentForUrl("https://play.google.com/store/apps/details");
        startActivity(rateIntent);
    }
}

private Intent rateIntentForUrl(String url)
{
    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(String.format("%s?id=%s", url, getPackageName())));
    int flags = Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_MULTIPLE_TASK;
    if (Build.VERSION.SDK_INT >= 21)
    {
        flags |= Intent.FLAG_ACTIVITY_NEW_DOCUMENT;
    }
    else
    {
        //noinspection deprecation
        flags |= Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET;
    }
    intent.addFlags(flags);
    return intent;
}

Ponga el código en el Activityque desea llamarlo.
Cuando el usuario hace clic en un botón para calificar la aplicación, simplemente llame a la rateApp()función.

György Benedek
fuente
Lo NuGet paquete debería añadir, y lo que debería ser espacio de nombres usingpara Intentser un tipo viable? Encontré Android.Content , pero estoy perdido con IntentXamarin Forms.
s3c
24

Siempre uso este código:

startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=PackageName")));
Cabezas
fuente
44
Siempre como un revestimiento. :)
androidStud
lo uso pero muestra este error: `android.content.ActivityNotFoundException: no se encontró actividad para manejar la intención {act = android.intent.action.VIEW dat = market: // details? id = PackageName}` - ¿qué puedo hacer? ?
Mina Dahesh
¿Puedes comprobar esto ?
Cabezas
@Cabezas. En general, quiero mostrar todo el mercado existente en el teléfono. haciendo clic en cuál de ellos, si mi aplicación existía, market muestra la aplicación. Entonces, ¿qué debo hacer?
Mina Dahesh
1
@Cabezas. uso este código: `try {Intent intent = new Intent (Intent.ACTION_VIEW); intent.setData (Uri.parse ("bazar: // detalles? id = vote_note.maxsoft.com.vownote")); intent.setData (Uri.parse ("myket: // comment? id = vote_note.maxsoft.com.vownote")); startActivity (intento); } catch (ActivityNotFoundException e1) {try {startActivity (new Intent (Intent.ACTION_VIEW, Uri.parse ("MARKET URL"))); startActivity (nueva intención (Intent.ACTION_VIEW, Uri.parse ("MARKET URL"))); } catch (ActivityNotFoundException e2) {Toast.} `
Mina Dahesh
18

Esto es si publica su aplicación tanto en Google Play Store como en Amazon Appstore. También manejo el caso de que los usuarios (especialmente en China) no tienen tanto la tienda de aplicaciones como el navegador.

public void goToMyApp(boolean googlePlay) {//true if Google Play, false if Amazone Store
    try {
       startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse((googlePlay ? "market://details?id=" : "amzn://apps/android?p=") +getPackageName())));
    } catch (ActivityNotFoundException e1) {
        try {
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse((googlePlay ? "http://play.google.com/store/apps/details?id=" : "http://www.amazon.com/gp/mas/dl/android?p=") +getPackageName())));
        } catch (ActivityNotFoundException e2) {
            Toast.makeText(this, "You don't have any app that can open this link", Toast.LENGTH_SHORT).show();
        }
    }
}
Hải Phong
fuente
No responde la pregunta en cuestión.
¿Qué pasa con el código para abrir la lista de la tienda de aplicaciones de Amazon de su aplicación?
isJulian00
Lo NuGet paquete debería añadir, y lo que debería ser espacio de nombres usingpara Intentser un tipo viable? Encontré Android.Content , pero estoy perdido con IntentXamarin Forms.
s3c
10

Siempre puede llamar a getInstalledPackages () desde la clase PackageManager y verificar para asegurarse de que la clase de mercado esté instalada. También podría usar queryIntentActivities () para asegurarse de que la intención que construya pueda ser manejada por algo, incluso si no es la aplicación del mercado. Esto es probablemente lo mejor que se puede hacer porque es el más flexible y robusto.

Puede verificar si la aplicación de mercado está allí

Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setData(Uri.parse("market://search?q=foo"));
PackageManager pm = getPackageManager();
List<ResolveInfo> list = pm.queryIntentActivities(intent, 0);

Si la lista tiene al menos una entrada, el Mercado está allí.

Puede usar lo siguiente para iniciar Android Market en la página de su aplicación, es un poco más automatizado:

Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse("market://details?id=" + getPackageName()));
startActivity(i);

Si desea probar esto en su emulador, probablemente no tenga instalado el mercado: consulte estos enlaces para obtener más detalles:

Cómo habilitar el Android Market en el emulador de Android de Google

Instalación de Google Play en el emulador de Android

K_Anas
fuente
¿Dónde en el androidmanifest.xml coloco este código? ¿Necesito agregar algo más? ¿Cómo corresponde eso a un enlace o botón real en una pantalla que el usuario presiona? Gracias
Adreno
8

Utilizo este enfoque para que el usuario califique mis aplicaciones:

public static void showRateDialog(final Context context) {
    AlertDialog.Builder builder = new AlertDialog.Builder(context)
            .setTitle("Rate application")
            .setMessage("Please, rate the app at PlayMarket")
            .setPositiveButton("RATE", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (context != null) {
                        String link = "market://details?id=";
                        try {
                            // play market available
                            context.getPackageManager()
                                    .getPackageInfo("com.android.vending", 0);
                        // not available
                        } catch (PackageManager.NameNotFoundException e) {
                            e.printStackTrace();
                            // should use browser
                            link = "https://play.google.com/store/apps/details?id=";
                        }
                        // starts external action
                        context.startActivity(new Intent(Intent.ACTION_VIEW, 
                                Uri.parse(link + context.getPackageName())));
                    }
                }
            })
            .setNegativeButton("CANCEL", null);
    builder.show();
}
gtgray
fuente
¿Para qué es esto? - market://details?id=El enlace de mi aplicación es comohttps:\\play.google.com\apps\details?id=
Sagar Balyan
2
@SagarBalyan, es una uri especial para abrir la página de su aplicación en la aplicación de mercado de Google Play. Si comienza la actividad con el enlace que proporcionó, Android abrirá la página de su aplicación en el navegador predeterminado o le dará la opción de qué aplicación de navegador comenzar
gtgray
5

Una versión de kotlin

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
    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
fuente
4

Puedes usar esto, me funciona

public static void showRateDialogForRate(final Context context) {
    AlertDialog.Builder builder = new AlertDialog.Builder(context)
            .setTitle("Rate application")
            .setMessage("Please, rate the app at PlayMarket")
            .setPositiveButton("RATE", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (context != null) {
                        ////////////////////////////////
                        Uri uri = Uri.parse("market://details?id=" + context.getPackageName());
                        Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
                        // To count with Play market backstack, After pressing back button,
                        // to taken back to our application, we need to add following flags to intent.
                        goToMarket.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY |
                                Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET |
                                Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
                        try {
                            context.startActivity(goToMarket);
                        } catch (ActivityNotFoundException e) {
                            context.startActivity(new Intent(Intent.ACTION_VIEW,
                                    Uri.parse("http://play.google.com/store/apps/details?id=" + context.getPackageName())));
                        }


                    }
                }
            })
            .setNegativeButton("CANCEL", null);
    builder.show();
}
Suman
fuente
4

Valoración de Play Store

 btn_rate_us.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Uri uri = Uri.parse("market://details?id=" + getPackageName());
                Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
                // To count with Play market backstack, After pressing back button,
                // to taken back to our application, we need to add following flags to intent.
                goToMarket.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY |
                        Intent.FLAG_ACTIVITY_NEW_DOCUMENT |
                        Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
                try {
                    startActivity(goToMarket);
                } catch (ActivityNotFoundException e) {
                    startActivity(new Intent(Intent.ACTION_VIEW,
                            Uri.parse("http://play.google.com/store/apps/details?id=" + getPackageName())));
                }
            }
        });
Keshav Gera
fuente
3

Otro enfoque que puede funcionar para usted es Linkify. Si tengo un TextView que le pide al usuario que califique la aplicación, puedo vincular un par de palabras en el texto para que estén resaltadas y cuando el usuario las toque, se abrirá Play Store, lista para su revisión:

class playTransformFilter implements TransformFilter {
   public String transformUrl(Matcher match, String url) {
        return "market://details?id=com.qwertyasd.yourapp";
   }
}

class playMatchFilter implements MatchFilter {
    public boolean acceptMatch(CharSequence s, int start, int end) {
        return true;
    }
}
text1 = (TextView) findViewById(R.id.text1);
text1.setText("Please rate it.");
final Pattern playMatcher = Pattern.compile("rate it");
Linkify.addLinks(text1, playMatcher, "", 
                   new playMatchFilter(), new playTransformFilter());
Granate Ulrich
fuente
3

Un punto con respecto a todas las respuestas que tienen implementaciones basadas en la estrategia getPackageName () es que usar BuildConfig.APPLICATION_ID puede ser más sencillo y funciona bien si usa la misma base de código para construir múltiples aplicaciones con diferentes identificadores de aplicación (por ejemplo, un producto de etiqueta blanca).

Hecht
fuente
2
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.StringRes;
import android.widget.Toast;

public class PlayStoreLink {

public void checkForUpdate(Context context, int applicationId) 
{
    try {
        context.startActivity(new Intent(Intent.ACTION_VIEW,
                Uri.parse(context.getString(R.string.url_market_details)
                        + applicationId)));
    } catch (android.content.ActivityNotFoundException anfe) {
        try {
            context.startActivity(new Intent(Intent.ACTION_VIEW,
                    Uri.parse(context.getString(R.string.url_playstore_app)
                            + applicationId)));
        } catch (Exception e) {
            Toast.makeText(context,
                    R.string.install_google_play_store,
                    Toast.LENGTH_SHORT).show();
        }
    }
}

public void moreApps(Context context, @StringRes int devName) {
    try {
        context.startActivity(new Intent(Intent.ACTION_VIEW,
                Uri.parse(context.getString(R.string.url_market_search_app)
                        + context.getString(devName))));
    } catch (android.content.ActivityNotFoundException anfe) {
        try {
            context.startActivity(new Intent(Intent.ACTION_VIEW,
                    Uri.parse(context.getString(R.string.url_playstore_search_app)
                            + context.getString(devName))));
        } catch (Exception e) {
            Toast.makeText(context,
                    R.string.install_google_play_store,
                    Toast.LENGTH_SHORT).show();
        }
    }
}

public void rateApp(Context context, int applicationId) {
    try {
        Uri uri = Uri.parse(context.getString(R.string.url_market_details)
                + applicationId);
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        int flags = Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_MULTIPLE_TASK;
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH)
            flags |= Intent.FLAG_ACTIVITY_NEW_DOCUMENT;
        else
            flags |= Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET;
        intent.addFlags(flags);
        context.startActivity(intent);
    } catch (ActivityNotFoundException e) {
        checkForUpdate(context, applicationId);
    }
}
}

<string name="install_google_play_store" translatable="false">Please install google play store and then try again.</string>
<string name="url_market_details" translatable="false">market://details?id=</string>
<string name="url_playstore_app" translatable="false">https://play.google.com/store/apps/details?id=</string>
<string name="url_market_search_app" translatable="false">market://search?q=pub:</string>
<string name="url_playstore_search_app" translatable="false">http://play.google.com/store/search?q=pub:</string>
<string name="app_link" translatable="false">https://play.google.com/store/apps/details?id=</string>

devName es el nombre de la cuenta de desarrollador en Play Store

Pratik Saluja
fuente
2

Puede usar este código simple para calificar su aplicación en su actividad.

try {
    Uri uri = Uri.parse("market://details?id=" + getPackageName());
    Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
    startActivity(goToMarket);
} catch (ActivityNotFoundException e) {
    startActivity(new Intent(Intent.ACTION_VIEW,
    Uri.parse("http://play.google.com/store/apps/details?id=" + getPackageName())));
}
SANJAY GUPTA
fuente
¿Para qué es esto? - market://details?id=El enlace de mi aplicación es comohttps:\\play.google.com\apps\details?id=
Sagar Balyan
@SagarBalyan Si el usuario tiene múltiples mercados de aplicaciones, abrirá la tienda predeterminada o le mostrará una intención para cada tienda disponible.
Avi Parshan
2

Utilizo el siguiente enfoque combinando esta y esta respuesta sin usar programación basada en excepciones y también es compatible con el indicador de intención anterior a API 21.

@SuppressWarnings("deprecation")
private Intent getRateIntent()
{
  String url        = isMarketAppInstalled() ? "market://details" : "https://play.google.com/store/apps/details";
  Intent rateIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(String.format("%s?id=%s", url, getPackageName())));
  int intentFlags   = Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_MULTIPLE_TASK;
  intentFlags      |= Build.VERSION.SDK_INT >= 21 ? Intent.FLAG_ACTIVITY_NEW_DOCUMENT : Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET;
  rateIntent.addFlags(intentFlags);
  return rateIntent;
}

private boolean isMarketAppInstalled()
{
  Intent marketIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://search?q=anyText"));
  return getPackageManager().queryIntentActivities(marketIntent, 0).size() > 0;
}


// use
startActivity(getRateIntent());

Dado que el indicador de intención FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESETestá en desuso de API 21, uso la @SuppressWarnings("deprecation")etiqueta en el método getRateIntent porque el SDK de destino de mi aplicación está por debajo de API 21.


También probé la forma oficial de Google sugerida en su sitio web (6 de diciembre de 2019). Por lo que veo, no maneja el caso si la aplicación Play Store no está instalada:

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);
Bruno Bieri
fuente
0

Declara un método en tu clase de actividad. Luego copie y pegue el siguiente código.

private void OpenAppInPlayStore(){

    Uri uri = Uri.parse("market://details?id=" + this.getPackageName());
    Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
    // To count with Play market backstack, After pressing back button,
    // to taken back to our application, we need to add following flags to intent.
    goToMarket.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY |
            Intent.FLAG_ACTIVITY_NEW_DOCUMENT |
            Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
    try {
        startActivity(goToMarket);
    } catch (ActivityNotFoundException e) {
        startActivity(new Intent(Intent.ACTION_VIEW,
                Uri.parse("http://play.google.com/store/apps/details?id=" + this.getPackageName())));
    }

}

Ahora llame a este método desde cualquier parte de su código.

Sigue la imagen de abajo de mi proyecto práctico.

ingrese la descripción de la imagen aquí

XpressGeek
fuente