Como abrir a Google Play Store diretamente do meu aplicativo Android?
abri a loja do google play usando o código de follwing
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);.
mas mostra-me uma área de Acção completa para seleccionar a opção (browser/play store). Preciso de abrir a aplicação na playstore directamente.
18 answers
Podes fazer isto usando o market://
prefixo.
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)));
}
Usamos um bloco try/catch
aqui porque um Exception
será lançado se a Loja de reprodução não estiver instalada no dispositivo de destino.
Nota : qualquer aplicação pode registar-se como capaz de lidar com o market://details?id=<appId>
Uri, se quiser visar especificamente o Google Play, verifique o Berťák resposta
Muitas respostas aqui sugerem a utilização Uri.parse("market://details?id=" + appPackageName))
para abrir o Google Play, mas eu acho que é insuficiente na verdade:
Algumas aplicações de terceiros podem usar seus próprios filtros de intenção com "market://"
esquema definido , assim eles podem processar URI fornecido em vez de Google Play (eu experimentei esta situação com P.ex. aplicação SnapPea). A questão é " como abrir a Play Store Google?", então eu assumo, que você não quer abrir qualquer outra aplicação. Por favor, note também, que, por exemplo, a classificação de app só é relevante em app Store etc...
Para abrir o Google Play e só o Google Play eu uso este método:
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);
}
}
O ponto é que quando mais aplicações ao lado do Google Play podem abrir a nossa intenção, a janela de selecção de aplicações é ignorada e a aplicação GP é iniciada directamente.
Actualização:
Às vezes parece que ele abre app GP apenas, sem abrir o perfil do app. Como TrevorWiley sugeriu em seu comentário, Intent.FLAG_ACTIVITY_CLEAR_TOP
poderia resolver o problema. Eu não ... ainda não o testei...)
Veja esta resposta para compreender o que Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
faz.
Vá em ligação oficial do desenvolvedor Android como tutorial passo a passo, Veja e obtenha o código para o seu pacote de aplicação a partir da play store se existir ou se não existirem aplicativos da play store, em seguida, abra a aplicação a partir do navegador web.
Ligação oficial do programador Android
Http://developer.android.com/distribute/tools/promote/linking.html
Ligação a uma página de Aplicação
A partir de um sítio web: http://play.google.com/store/apps/details?id=<package_name>
market://details?id=<package_name>
Ligação a uma lista de Produtos
A partir de um sítio web: http://play.google.com/store/search?q=pub:<publisher_name>
market://search?q=pub:<publisher_name>
Ligação a um resultado de Pesquisa
A partir de um sítio web: http://play.google.com/store/search?q=<search_query>&c=apps
market://search?q=<seach_query>&c=apps
Tenta isto
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("market://details?id=com.example.android"));
startActivity(intent);
Todas as respostas acima abrem o Google Play em uma nova Vista do mesmo aplicativo, se você realmente quiser abrir o Google Play (ou qualquer outro aplicativo) de forma independente:
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);
A parte importante é que realmente abre Google play ou qualquer outro aplicativo de forma independente.
A maior parte do que vi usa a abordagem das outras respostas e não era o que eu precisava, espero que isto ajude alguém.Cumprimentos.
Pode verificar se a aplicaçãoGoogle Play Store está instalada e, se for esse o caso, pode usar o protocolo"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);
Mercado de Utilização:/ /
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + my_packagename));
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)));
}
Ao usar setPackage
, Forces o dispositivo a usar a Loja de reprodução. Se não houver nenhuma Play Store instalada, o Exception
será capturado.
Podes fazer:
final Uri marketUri = Uri.parse("market://details?id=" + packageName);
startActivity(new Intent(Intent.ACTION_VIEW, marketUri));
Obter referência aqui:
Você também pode tentar a abordagem descrita na resposta aceita desta pergunta: não é possível determinar se o Google play store está instalado ou não no dispositivo Android
Solução pronta a usar:
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)));
}
}
}
Baseado na resposta do Eric.
Se quiser abrir a Google Play store a partir da sua aplicação, então use este comando directy: market://details?gotohome=com.yourAppName
, irá abrir as páginas do Google Play store da sua aplicação.
- Web: http://play.google.com/store/apps/details?id=
- App: Mercado: / / detalhes?id =
Mostra todas as aplicações por uma editora específica
- Web: http://play.google.com/store/search?q=pub:
- App: mercado: / / pesquisa?q=pub:
Procura por aplicações que usem a consulta em o seu título ou descrição
- Web: http://play.google.com/store/search?q=
- App: mercado: / / pesquisa?q=
Referência: https://tricklio.com/market-details-gotohome-1/
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)));
}
}
A minha função de intensidade de kotlin para este efeito
fun Context.canPerformIntent(intent: Intent): Boolean {
val mgr = this.packageManager
val list = mgr.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY)
return list.size > 0
}
E na sua actividade
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))
Aqui está o código final das respostas acima que as primeiras tentativas de abrir o aplicativo usando o Google play store app e especificamente play store, se falhar, ele irá iniciar a área de ação usando a versão web: Créditos 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);
}
}
Eu combinei ambos Berťák e Stefano Munarini a resposta para criar uma solução híbrida que lida com ambos a taxa deste App e Mostra Mais App cenário.
/**
* 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);
}
}
Utilização
- Para Abrir O Perfil Dos Editores
@OnClick(R.id.ll_more_apps) public void showMoreApps() { openPlayStore(true, "Hitesh Sahu"); }
- para abrir uma página de aplicações na PlayStore
@OnClick(R.id.ll_rate_this_app) public void openAppInPlayStore() { openPlayStore(false, ""); }
Este link irá abrir o aplicativo automaticamente no mercado:// se você estiver no Android e no navegador se você estiver no PC.
https://play.app.goo.gl/?link=https://play.google.com/store/apps/details?id=com.app.id&ddl=1&pcampaignid=web_ddl_1
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")))
}
}
Se quiser abrir o mercado de jogo para procurar aplicações( por exemplo, "pdf"), use isto:
private void openPlayMarket(String query) {
try {
// If Play Services are installed.
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://search?q=" + query)));
} catch (ActivityNotFoundException e) {
// Open in a browser.
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/search?q=" + query)));
}
}