この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。
Intent filterの実装
- 特定のURLを押した際に、指定した画面を開くようにします
- 今回はサンプルのURLを利用
https://dev.classmethod.jp/sample-path/
<activity android:name=".SampleActivity" >
<intent-filter android:autoVerify="true">
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:host="dev.classmethod.jp"
android:pathPrefix="/sample-path"
android:scheme="http"/>
</intent-filter>
</activity>
SampleActivityにてIntentを受け取り、URLからアプリを開いた際の挙動を実装します
Intent intent = getIntent();
String action = intent.getAction();
Uri data = intent.getData();
if (Intent.ACTION_VIEW.equals(action) && data != null) {
// FIXME URLからアプリを開いた時に行う処理
}
Webサイトとアプリの紐付け
- Developer Consoleにてアプリを公開します。
- Google Search Consoleにて
android-app://{package-name}/
形式でアプリを登録します。- Developer Consoleと同じアカウントで行うことで、申請・許可の作業が減ります詳しくはこちら
- 以下継続
インデックス登録するページを指定
ここが今回の本題です。今までの作業はFirebaseが新しくなる前のAppIndexing実装と大差ありません。
導入
Firebase全体の導入までは完了している前提です。 以下を追記。
dependencies {
...
compile 'com.google.android.gms:play-services-appindexing:9.4.0'
...
}
実装
登録するページにてAppIndexingAPIを利用します。
private GoogleApiClient mClient;
private String sampleId = "hoge"; // FIXME ページ番号
private static final String TITLE = "Sample"; // FIXME ページタイトル
@Override
public void onStart(){
super.onStart();
if (sampleId != null) {
mClient.connect();
final Uri BASE_URL = Uri.parse("https://dev.classmethod.jp/sample-path/");
final Uri APP_URI = BASE_URL.buildUpon().appendPath(sampleId).build();
Action viewAction = Action.newAction(Action.TYPE_VIEW, TITLE, APP_URI);
PendingResult<Status> result = AppIndex.AppIndexApi.start(mClient, viewAction);
result.setResultCallback(new ResultCallback<Status>() {
@Override
public void onResult(Status status) {
if (status.isSuccess()) {
// FIXME 登録成功処理(フラグの登録など)
} else {
// FIXME 登録失敗処理(ログ出力など)
}
}
});
}
}
@Override
public void onStop(){
if (sampleId != null) {
final Uri BASE_URL = Uri.parse("https://dev.classmethod.jp/sample-path/");
final Uri APP_URI = BASE_URL.buildUpon().appendPath(sampleId).build();
Action viewAction = Action.newAction(Action.TYPE_VIEW, TITLE, APP_URI);
PendingResult<Status> result = AppIndex.AppIndexApi.end(mClient, viewAction);
result.setResultCallback(new ResultCallback<Status>() {
@Override
public void onResult(Status status) {
if (status.isSuccess()) {
// FIXME 終了処理成功処理(フラグの削除など)
} else {
// FIXME 終了処理失敗処理(ログ出力など)
}
}
});
mClient.disconnect();
}
super.onStop();
}
Activityで行う場合は、上記のようにonStart, onStopでstartとend処理を行えば問題ありません。 Fragmentで行う場合は、以下の点に注意が必要です。
- 同じFragmentから複数回APIを呼ばない
- e.g., SampleFragmentから
http://sample.jp/hoge/
を二重登録しないようにする - end後ならば、再度startしても良い
- e.g., SampleFragmentから
あとがき
実装はシンプルですが、動作確認がすぐにできない点が面倒ですね。 Google Search Consoleを使う方法以外にも、Digital Asset Linksを利用する方法もあるようなので、 今後より詳しく調べていこうと思います。