ユーザ用ツール

文書の過去の版を表示しています。


暗黙のインテント

概要

インテント-殊に暗黙のインテントは、AndroidをiOSと大きく差別化している最大のものであるといえる。 コレがあるが故に、Androidはデータをアプリ間で自由に共有でき、ツイッターへ投稿する、写真を公開するなどの処理を、他のアプリに依頼する形で、実装せずとも利用できるのである。

ここでは、暗黙のインテントに関する事柄について記しておく。

画像をギャラリーから取得する

プログラムから、以下のように、TypeとActionを指定して、暗黙のインテントを起動する。戻りは、onActivityResult()で受け取る。必要に応じて、requestCodeをチェックすること。

Intent gi = new Intent();
gi.setType("image/*");
gi.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(gi, GALLERY_REQUEST);

画像はURIで渡されるので、受け取ったら、InputStream経由でBitmapへと取り出す。

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO 自動生成されたメソッド・スタブ
     super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == GALLERY_REQUEST && resultCode == RESULT_OK)
    {
        try {
            URI uri = data.getData();
            InputStream is = getContentResolver().openInputStream(uri);
            Bitmap bitmap = BitmapFactory.decodeStream(is);
            is.close();
        }

画像をインテント経由で受け取る

インテントからデータを受け取るためには、受け取りたい Activityに Intent-filterを定義してやる必要がある。Manifest ファイルで、

<intent-filter>
    <action android:name="android.intent.action.SEND"/>
    <category android:name="android.intent.category.DEFAULT"/>
    <data android:mimeType="image/jpeg"/>
    <data android:mimeType="image/jpg"/>
    <data android:mimeType="image/png"/>
    <data android:mimeType="image/gif"/>
</intent-filter>

のように、action/category そして、dataを定義してやる。 画像は、image/* でも受け取ることが出来るが、動画など、期待していないタイプまで引き渡される可能性があるので、受け取りたいものだけを列記しておいた方が良いだろう。

プログラム側では、onCreate()の中で、次のようにデータを受け取る。URIはParcelableで渡されてくるので注意。Stringなどではないので、誤った受け取り方をすると、NullPointer例外などを引き起こす。

Intent intent = getIntent();
String action = intent.getAction();
if (Intent.ACTION_SEND.equals(action))
{
    Bundle params = intent.getExtras();
    if (params != null)
    {
        String type = intent.getType();
        if (type.startsWith("image/"))
        {
            Uri uri = params.getParcelable(Intent.EXTRA_STREAM);
            try {
                InputStream is = getContentResolver().openInputStream(uri);
                Bitmap bitmap = BitmapFactory.decodeStream(is);
                is.close();
            }

テキストをインテント経由で受け取る

Androidに関してへ戻る。

This website uses cookies. By using the website, you agree with storing cookies on your computer. Also, you acknowledge that you have read and understand our Privacy Policy. If you do not agree, please leave the website.

More information