ブラウザのリンクをクリックすると特定のアプリが起動する というもの。
まずはHTML側のページを作成
<a href="[scheme]://[host]/[path]?[query]">アプリを起動</a>
この一文でOK
各項目の意味は以下
- scheme:起動するアプリを判別 ※後述に詳細
- host:適当に記述←
- path:値を受け渡すときに必要なキー ※無くても大丈夫
- query:値を取得するKeyとValueを書く ※無くても大丈夫
試しにちゃんと書いてみるとこんな感じになる↓
<a href="myapp://jp.app/openwith?name=テスト&age=26">アプリを起動</a>
次にAndroid側
まずAndroidManifest.xmlに以下を追加。(起動するActivityに付与)
※必須
<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="myapp" android:host="jp.app" android:pathPrefix="/openwith"/>
</intent-filter>
HTML側で記述したものは<data …/>に入る形になる。
この中で必須なのはscheneのみで、その他は無くてもアプリは起動できるようです。
ここで注意事項として、intent-filterの内部では【android.intent.action.MAIN】と【android.intent.category.LAUNCHER】の二つを今回追加するものと混合してはいけないようです。
なのでもし一緒のActivityに入れる場合は以下のようにして下さい。
<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="myapp" android:host="jp.app" android:pathPrefix="/openwith"/>
</intent-filter>
こうすれば問題ありません。
次に値の取得
起動するActivityのお好きなタイミングに以下を追加。
Intent i_getvalue = getIntent();
String action = i_getvalue.getAction();
if(Intent.ACTION_VIEW.equals(action)){
Uri uri = i_getvalue.getData();
if(uri != null){
String name = uri.getQueryParameter("name");
String age= uri.getQueryParameter("age");
}
}
以上で値が取得できます。
使いどころがあんまり無いかもしれないけど、今回使う必要があったのでメモしてみました(´,,・ω・,,`)
