暗黙的なIntentを作成する
Androidで、どのアプリからも呼び出すことができる公開されたIntentを作りたい。
このようなIntentのことは、暗黙的なIntent(Implicit Intents)というようだ。呼び出す側がIntentのクラス名を明示しないため、「暗黙的(Implicit)」という言葉を使っているのだろう。クラス名の代わりにアクションを指定して、ユーザーにどのIntentを利用するか選ばせることになる。
Intentについては、id:minghaiさんの記事が詳しくてわかりやすいので、参考にさせていただいた。
他にも、公式のガイド、リファレンスが参考になった。
最終的には、オリジナルなアクションを定義したいが、差し当たって、URLを開くアクションで起動するIntentを作成する。
1.呼び出し側の準備
コードを書いてもよいが、今回はadbのamコマンドを使ってみる。
まずは、ブラウザを呼び出してみる。
// エミュレータ起動後に、以下のコマンドを実行。
> adb shell
# am start -a android.intent.action.VIEW -d http://www.google.com -t text/html
すると、エミュレータ内でブラウザが起動して、googleのページが表示される。なお、amコマンドのオプションは、コマンドプロンプトに"am"とだけ入力すれば表示される。
2.呼び出される側の準備
暗黙的なIntentの呼び出し時に引っかかるようにする。『初めてのAndroid 第3版』のHelloAndroidアプリのAndroidManifest.xmlにintent-filterタグを追加して、1のようにしてURLを開くときに呼び出されるIntentを作る。
<activity android:name=".Hello" android:label="@string/app_name"> <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" /> <data android:scheme="http" android:mimeType="text/html" /> </intent-filter> </activity>
はまったところ
- "android.intent.action.ACTION_VIEW"ではなく、"android.intent.action.VIEW"。ソースコードでIntentを作るときは、new Intent(Intent.ACTION_VIEW)。
- 暗黙的なIntentのときは、"android.intent.category.DEFAULT"の指定が必須
3.実行
// エミュレータ起動後に、以下のコマンドを実行。
> adb shell
# am start -a android.intent.action.VIEW -d http://www.google.com -t text/html
これで、以下のようにIntentを選択するダイアログが出てきたら成功。
出ないでブラウザが立ち上がる場合、ブラウザがデフォルトのアプリケーションに設定されている可能性がある。デフォルトのアプリケーションを解除する方法は、"Home Settings > Applications > Manage applications"。