2012年8月2日木曜日

特定のURLをフックしてアプリを起動させる(暗黙的インテント)

やりたいこと
・特定のURLクリック時にアプリをインストールしている場合はアプリケーション選択ダイアログが出て、ブラウザで遷移するかアプリを起動するか選べる
・アプリをインストールしていない場合は普通にページ遷移

具体的に言うと、オンエアー中のアニメのタイムラインを見に行こうとするとアプリケーションに移動するか、スマフォサイトで用意したページに行くか選べるようにしたいってこと。

まず、AndroidManifest.xmlを変更

<activity
android:name=".Test"
android:label="@string/test.title">
<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="http"
android:host="test.tsubuani.com"
android:pathPrefix="/live" />
</intent-filter>
</activity>
intent-filterにaction.View,category.DEFAULT,cateogry.BROWSABLEを追加。
dataにscheme,host,pathPrefixを追加。
schemeやhostとかはそれぞれ依存しているので注意が必要。
pathPrefixの他にも、pathやpathPatternなんてのも指定できる。
細かい仕様は下記参照。
http://www.techdoctranslator.com/android/guide/manifest/data-element

今回の例で言うと

http://test.tsubuani.com/live*******
っていうURLにアクセスしようとするとTestActivityが起動するという感じになる。

ActivityはonNewIntentに処理を書いてやればよい

@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);

Intent intent = getIntent();
if( intent != null ) {
/** リンク先のURLを取得する。 */
String data = intent.getDataString();
if(data != null){
//urlを元にごにょごにょ
}
}
}

これで、アプリをインストールしている人はアプリで実況TLを見ることが出来るし、
そうでない人はスマフォサイトで用意したページに遷移させることが出来る。
Androidはこんな感じでアプリ同士の連携がすごい簡単に出来るのが素敵。

AndroidManifest.xmlに記述したの取得方法

この方法を使うとアプリケーションで固定して使う値を一元管理出来ます。

strings.xmlで管理する方法もありますがどちらがいいのでしょうか?

とりあえず、AndroidManifest.xmlに以下のように<meta-data>を記述します。

<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".TestDroid"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

<meta-data android:value="test_value" android:name="test_key" />
</application>
10行目がmeta-dataの記述です。

この値をプログラム側で取得する方法です。

ApplicationInfo appliInfo = null;
try {
appliInfo = getPackageManager().getApplicationInfo(getPackageName(),
PackageManager.GET_META_DATA);
} catch (NameNotFoundException e) {}
Log.d("MetaData", appliInfo.metaData.getString("test_key"));
このように記述します。

ちなみに、例はActivityの中での使用方法なので、

Contextのメソッドの「getPackageManager」や「getPackqgeName」は適時インスタンス変数からの呼び出しに変更してください。