LoginSignup
3
0

More than 3 years have passed since last update.

Nuxt.jsでURLスキームを利用してAndroidアプリを起動

Posted at

Nuxt.jsでWebページを作成した場合の、URLスキームでのAndroidアプリ起動方法をまとめておきます。

nuxt-user-agentを導入

Android端末かの判定に nuxt-user-agent を使用します。
下記コマンドで、Nuxt.jsのプロジェクトにインストールしてください。

npm install -S nuxt-user-agent

nuxt.cofig.js ファイルに、設定を追加します。

nuxt.config.js
modules: [
  'nuxt-user-agent'
],

middlewareの作成

ユーザーエージェントを判定して、アプリ起動やストア移動を行うmiddlewareを作成します。
const ANDROID_SCHEME = 'sample://app'; の部分で、Androidアプリを起動するURLスキームを指定しています。

middleware/launch-app.js
export default (context) => {
  const ANDROID_SCHEME = 'sample://app';
  const isFromAndroidOs = context.$ua.isFromAndroidOs();

  if(isFromAndroidOs) {
    document.location = 'intent://#Intent;scheme=' + ANDROID_SCHEME + ';end';
  }
}

上記のmiddlewareを使用したいページで、middlewareの読み込みを行います。
例として、 pages/index.vue で読み込みを行っています。

pages.index.vue
<script>
export default {
  middleware: 'launch-app'
}
</script>

Androidアプリ側にアプリ起動用のURLスキームを設定する

Androidアプリ側に、Nuxt.jsで作成したWebページから起動するためのURLスキームを設定します。
マニフェストファイルに下記を追記するだけです。
sample://app でアプリが起動するように設定しています。

AndroidManifest.xml
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

            <!-- 追加ここから -->
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
                <data android:scheme="sample" android:host="app" />
            </intent-filter>
            <!-- 追加ここまで -->

        </activity>
    </application>

これらの設定が終わると、Androidアプリがインストールされた端末でWebページを表示した際に、アプリが起動するようになります。

3
0
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
3
0