내 Android 애플리케이션에서 직접 Google Play 스토어를 여는 방법은 무엇입니까?


569

다음 코드를 사용하여 Google Play 스토어를 열었습니다.

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

그러나 옵션 (브라우저 / 플레이 스토어)을 선택하는 완전한 작업보기가 표시됩니다. Play 스토어에서 애플리케이션을 직접 열어야합니다.


답변:


1436

market://접두사를 사용하여이 작업을 수행 할 수 있습니다 .

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

대상 기기에 Play 스토어가 설치되어 있지 않으면이 try/catch블록이 사용 되므로 여기서 블록을 사용합니다 Exception.

참고 : market://details?id=<appId>Google Play를 구체적으로 타겟팅하려면 Berťák 답변을 확인하려는 경우 모든 앱이 Uri 를 처리 할 수있는 것으로 등록 할 수 있습니다


53
모든 개발자의 애플리케이션 사용에 리디렉션하려는 경우 market://search?q=pub:"+devName와http://play.google.com/store/search?q=pub:"+devName
— 스테파노 Munarini

4
일부 응용 프로그램에서 "market : //"체계가 정의 된 의도 필터를 사용하는 경우이 솔루션이 작동하지 않습니다. Google Play 및 Google Play 응용 프로그램 (GP가없는 경우 웹 브라우저) 만 여는 방법에 대한 답변을 참조하십시오. :-)
— Berťák

18
Gradle 빌드 시스템을 사용하는 프로젝트의 경우 appPackageName실제로 BuildConfig.APPLICATION_ID입니다. 아니요 Context/ Activity종속성으로 인해 메모리 누수 위험을 줄입니다.
— Christian García

3
의도를 시작하려면 여전히 컨텍스트가 필요합니다. Context.startActivity ()
— wblaschko

2
이 솔루션은 웹 브라우저를 열려는 의도가 있다고 가정합니다. 항상 그렇지는 않습니다 (Android TV 에서처럼). intent.resolveActivity (getPackageManager ())를 사용하여 수행 할 작업을 결정할 수 있습니다.
— Coda

161

여기에 많은 답변이 Uri.parse("market://details?id=" + appPackageName)) Google Play를 여는 데 사용 하는 것이 좋지만 실제로 는 충분하지 않다고 생각합니다 .

일부 타사 응용 프로그램은 "market://"scheme 정의 된 자체 인 텐트 필터를 사용할 수 있으므로 Google Play 대신 제공된 Uri를 처리 할 수 ​​있습니다 (예 : 이러한 상황은 egSnapPea 응용 프로그램에서 발생했습니다). 문제는 "Google Play 스토어를 여는 방법"입니다. 따라서 다른 응용 프로그램을 열고 싶지 않다고 가정합니다. 예를 들어 앱 등급은 GP Store 앱 등에 만 관련이 있습니다.

Google Play와 Google Play 만 열려면이 방법을 사용합니다.

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

요점은 Google Play 이외의 더 많은 응용 프로그램이 우리의 의도를 열 수 있으면 응용 프로그램 선택 대화 상자를 건너 뛰고 GP 응용 프로그램을 직접 시작한다는 것입니다.

업데이트 : 때로는 앱의 프로필을 열지 않고 GP 앱 만 여는 것처럼 보입니다. TrevorWiley가 자신의 의견에서 제안한 것처럼 Intent.FLAG_ACTIVITY_CLEAR_TOP문제를 해결할 수 있습니다. (아직 테스트하지 않았습니다 ...)

무엇을 이해하려면 이 답변 을 참조하십시오 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED.


4
이것은 현재 Google Play 빌드에서는 신뢰할 수없는 것처럼 보이지만 Google Play에서 다른 앱 페이지를 입력 한 다음이 코드를 트리거하면 Google Play가 열리지 만 앱으로 이동하지는 않습니다.
— zoltish

2
@zoltish, 나는 플래그에 Intent.FLAG_ACTIVITY_CLEAR_TOP을 추가하고 문제를 해결하는 것 같습니다
— TrevorWiley

Intent.FLAG_ACTIVITY_CLEAR_TOP을 사용했습니다. | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED이지만 작동하지 않습니다. Play 스토어를 오픈 한 인스턴스가 없습니다
— Praveen Kumar Verma

3
rateIntent.setPackage("com.android.vending")PlayStore 앱이이 코드를 대신하여이 의도를 처리 하도록 하려면 어떻게됩니까 ?
— dum4ll3

3
@ dum4ll3 할 수 있다고 생각하지만이 코드는 Google Play 앱이 설치되어 있는지 암시 적으로 확인합니다. 확인하지 않으면 ActivityNotFound
— Daniele Segato를 만나야합니다.

81

단계별로 튜토리얼로 Android 개발자 공식 링크로 이동하여 Play 스토어에서 애플리케이션 패키지에 대한 코드를 보거나 가져 오거나 Play 스토어 앱이 없으면 웹 브라우저에서 애플리케이션을 엽니 다.

안드로이드 개발자 공식 링크

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

응용 프로그램 페이지에 연결

웹 사이트에서 : https://play.google.com/store/apps/details?id=<package_name>

Android 앱에서 : market://details?id=<package_name>

제품 목록에 연결

웹 사이트에서 : https://play.google.com/store/search?q=pub:<publisher_name>

Android 앱에서 : market://search?q=pub:<publisher_name>

검색 결과에 연결

웹 사이트에서 : https://play.google.com/store/search?q=<search_query>&c=apps

Android 앱에서 : market://search?q=<seach_query>&c=apps


market : // 접두사를 더 이상 사용하지 않는 것이 좋습니다 (게시 한 링크 확인)
— Greg Ennis

@GregEnnis 어디에서 market : // 접두사가 더 이상 권장되지 않습니까?
— loki

@ loki 요점은 더 이상 제안으로 나열되지 않는다는 것입니다. 해당 페이지에서 단어를 검색 market하면 해결책이 없습니다. 새로운 방법은보다 일반적인 의도의 developer.android.com/distribute/marketing-tools/… 를 해고하는 것이라고 생각합니다 . 최신 버전의 Play 스토어 앱에는 아마도이 URI에 대한 의도 필터가있을 것입니다.https://play.google.com/store/apps/details?id=com.example.android
— tir38

25

이 시도

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

1
Google Play를 독립적으로 여는 방법 (같은 앱의 새로운보기에 포함되지 않음)에 대한 답변을 확인하십시오.
— code4jhon

21

실제로 Google Play (또는 다른 앱)를 독립적으로 열려면 위의 모든 답변이 동일한 앱의 새로운보기에서 Google Play를 엽니 다.

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

중요한 부분은 실제로 Google Play 또는 다른 앱을 독립적으로 여는 것입니다.

내가 본 것의 대부분은 다른 답변의 접근 방식을 사용하며 이것이 누군가에게 도움이되기를 바라는 것은 아닙니다.

문안 인사.


무엇입니까 this.cordova? 변수 선언은 어디에 있습니까? 어디에서 callback선언되고 정의됩니까?
— Eric

이것은 당신이 단지 패키지 매니저의 인스턴스를 필요로하고 정기적 방식으로 활동을 시작 ... 코르도바 플러그인의 일부, 나는 그것이 실제로 관련이 있다고 생각하지 않는다지만이의 코르도바 플러그인입니다 github.com/lampaa 하는 I 덮어 여기 github.com/code4jhon/org.apache.cordova.startapp
— code4jhon

4
요점은 간단히 말해서,이 코드는 사람들이 사용하기 위해 단순히 자신의 앱으로 이식 할 수있는 것이 아닙니다. 지방을 다듬고 핵심 방법을 그대로 두는 것은 미래 독자들에게 유용 할 것입니다.
— Eric

예, 이해합니다 ... 현재 하이브리드 앱을 사용하고 있습니다. 완전히 원시 코드를 테스트 할 수는 없습니다. 하지만 아이디어가 있다고 생각합니다. 기회가 있으면 정확한 기본 줄을 추가합니다.
— code4jhon

잘만되면 이것이 @eric 될 것입니다
— code4jhon

14

Google Play 스토어 앱이 설치되어 있는지 확인할 수 있으며이 경우 "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
Google Play를 독립적으로 여는 방법 (같은 앱의 새로운보기에 포함되지 않음)에 대한 답변을 확인하십시오.
— code4jhon

12

Eric의 대답은 정확하지만 Berťák의 코드도 작동합니다. 나는 이것이 더 우아하게 결합된다고 생각합니다.

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

을 사용 setPackage하면 기기에서 Play 스토어를 사용하게됩니다. Play 스토어가 설치되어 있지 않으면가 Exception발견됩니다.


공식 문서 https://play.google.com/store/apps/details?id=는 market:어떻게 오나요? developer.android.com/distribute/marketing-tools/… 여전히 포괄적이고 짧은 답변입니다.
— serv-inc

확실하지 않지만 Android가 " play.google.com/store/apps "로 변환하는 바로 가기라고 생각합니다 . 예외적으로 "market : //"를 사용할 수도 있습니다.
— M3-n50 2018 년

11

market : // 사용

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

7

넌 할 수있어:

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

여기에서 참조 하십시오 :

이 질문에 대한 답변에서 설명한 방법을 시도해 볼 수도 있습니다 . Android 기기에 Google Play 스토어가 설치되어 있는지 여부를 확인할 수 없습니다


이 코드로 이미 시도했지만 장치에 두 앱 (Google Play 스토어 / 브라우저)이 설치되어 있기 때문에 브라우저 / 플레이 스토어를 선택하는 옵션도 표시됩니다.
— Rajesh Kumar

Google Play를 독립적으로 여는 방법 (같은 앱의 새로운보기에 포함되지 않음)에 대한 답변을 확인하십시오.
— code4jhon

7

파티에서 늦게 공식 문서 가 여기 있습니다. 그리고 설명 된 코드는

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

이 의도를 구성 할 때, 통과 "com.android.vending"에 Intent.setPackage()사용자가에서 앱의 세부 정보를 볼 수 있도록 구글 플레이 스토어 앱 대신 츄 . 코 틀린

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)

Google Play Instant를 사용하여 인스턴트 앱을 게시 한 경우 다음과 같이 앱을 시작할 수 있습니다.

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

코 틀린

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)

나는 이것이 틀렸다고 생각한다 Uri.parse("https://play.google.com/store/apps/details?id=. 일부 기기에서는 Play 마켓 대신 웹 브라우저를 엽니 다.
— CoolMind 2019

모든 코드는 공식 문서에서 가져 왔습니다. 응답 코드에 링크도 첨부되어 있으며 빠른 참조를 위해 여기에 설명되어 있습니다.
— Husnain Qasim

@CoolMind 그 이유는 해당 기기에 해당 URI와 일치하는 인 텐트 필터가없는 이전 버전의 Play 스토어 앱이 있기 때문일 수 있습니다.
— tir38

@ tir38, 아마도. Google Play 서비스가 없거나 권한이없는 것일 수도 있습니다. 기억이 나지 않습니다.
— CoolMind

6

으로 공식 문서를 사용하는 https://대신에 market://,이 수확기 에릭의 코드 재사용와 M3-N50의 대답 (중복 배제) :

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

GPlay 앱이 있으면 열려고 기본으로 돌아갑니다.


5

즉시 사용 가능한 솔루션 :

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

}

에릭의 답변을 바탕으로합니다.


1
그것은 당신을 위해 작동합니까? 내 앱 페이지가 아닌 기본 Google Play 페이지가 열립니다.
— 바이올렛 기린

4

코 틀린 :

신장:

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

방법:

    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

앱에서 Google Play 스토어를 열려면이 명령 directy :를 사용하면 market://details?gotohome=com.yourAppName앱의 Google Play 스토어 페이지가 열립니다.

특정 게시자의 모든 앱 표시

제목이나 설명에서 검색어를 사용하는 앱 검색

참조 : https://tricklio.com/market-details-gotohome-1/


3

코 틀린

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

이 목적을위한 나의 kotlin 텐션 기능

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

그리고 당신의 활동에서

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

위의 답변 중 마지막 코드는 Google Play 스토어 앱을 사용하여 앱을 열려고 시도하고, 특히 Play 스토어를 실패하면 웹 버전을 사용하여 작업보기를 시작합니다. 크레딧은 @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

이 링크는 Android에 있으면 market : //에 있고 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 2016 년

실제로 내 작업에는 웹보기가 있으며 웹보기에는 URL을로드해야합니다. 그러나 playstore URL이 열려 있으면 open playstore 버튼이 표시됩니다. 해당 버튼을 클릭하면 앱을 열어야합니다. 모든 응용 프로그램에 동적이므로 어떻게 관리 할 수 ​​있습니까?
— hpAndro

링크를 사용해보십시오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

Berťák 과 Stefano Munarini의 답변을 결합 하여이 앱 평가 및 더 많은 앱 표시 시나리오를 모두 처리하는 하이브리드 솔루션을 만들었습니다 .

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

용법

  • 게시자 프로필을 열려면
   @OnClick(R.id.ll_more_apps)
        public void showMoreApps() {
            openPlayStore(true, "Hitesh Sahu");
        }
  • PlayStore에서 앱 페이지를 열려면
@OnClick(R.id.ll_rate_this_app)
public void openAppInPlayStore() {
    openPlayStore(false, "");
}

이 코드를 더 작은 방법으로 나누는 것이 좋습니다. 그것은이 스파게티에 중요한 코드를 찾기 어렵다 :) 플러스 맞는 내용임을 확인 "com.android.vending" 무엇에 대한 com.google.market
— Aetherna

1

여러분, 실제로 더 많은 것을 얻을 수 있다는 것을 잊지 마십시오. 예를 들어 UTM 추적을 의미합니다. 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

폴백 및 현재 구문이있는 코 틀린 버전

 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)
    }
}
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.