10
8

More than 5 years have passed since last update.

Androidで自身のアプリのPlay Storeを開く

Posted at

Androidで自身のアプリのPlay Storeを開く

まずは結論

以下のコードが良いようです。

    fun openMyAppPlayStore() {
        val id = BuildConfig.applicationIdForStore
        try {
            context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + id)))
        } catch (anfe: android.content.ActivityNotFoundException) {
            context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + id)))
        }
    }

BuildConfig.applicationIdForStoreは追加で設定したもので詳細は後で記載します。

コード解説

try-catchしているandroid.content.ActivityNotFoundExceptionはPlay Storeアプリを無効にしているAndroid端末で発生します。

例外発生時はブラウザでPlay Storeを開く実装にしていますが、Play Storeアプリが無効だとアプリのインストールができないので、エラーメッセージの方が良いかもしれません。

BuildConfig.applicationIdForStore

Android開発ではBuild Variants毎にapplicationIdSuffixを付与していることが多いと思います。

android {
    buildTypes {
        debug {
            applicationIdSuffix = ".debug"
        }
        staging {
            applicationIdSuffix ".stg"
        }
        release {
        }
    }
}

このような環境でBuildConfig.APPLICATION_IDを使ってPlayStoreを開くとrelease以外はSuffixが付与されているため正常に動作しません。

そのためいずれのBuild Variantsでも正常にPlay Storeを開けるようにSuffixなしのApplicationIdを参照できるようにBuildConfig.applicationIdForStoreを追加しました。

独自のBuildConfigの値はbuild.gradleで以下のように設定できます。

android {
    defaultConfig {
        applicationId "com.hoge.fuga"
        // Play Store遷移時に Suffix なしの applictionId が必要なため追加します。
        buildConfigField "String", "applicationIdForStore", "\"${applicationId}\""
    }
}

参考にしたページ

10
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
8