Webブラウザーの「ページの共有」メニューからURLを受け取る - Android

Webブラウザの[その他]メニューの[ページを共有]メニューをクリックした際にページのURLをアプリケーションで受け取るコードを紹介します。

事前準備

こちらの記事を参照して、Webブラウザの[その他]メニューの[ページを共有]メニューにアプリケーションを追加するプログラムを作成します。

UI

元のプログラムから変更はありません。

コード

以下のコードを追記します。

IntentReceiveActivity.java

package iPentec.SimpleApp.IntentReceive;

import android.app.Activity;
import android.os.Bundle;
import android.content.*;
import android.widget.*;

public class IntentReceiveActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
        
      Intent intent = getIntent();
      String action = intent.getAction();
      if (Intent.ACTION_SEND.equals(action)) {
        Bundle extras = intent.getExtras();
        if (extras != null) {
          CharSequence ext = extras.getCharSequence(Intent.EXTRA_TEXT);
          if (ext != null) {
            TextView textView1 = (TextView)findViewById(R.id.textView1);
            textView1.setText(ext);
          }
        }
      }
    }
}

解説

Intent intent = getIntent();
String action = intent.getAction();
にて、インテントとインテントのアクションを取得します。

if (Intent.ACTION_SEND.equals(action)) {
  ...
}
今回はSENDのアクションに対応するため、アクションの種類がSENDであることとを確認します。

  Bundle extras = intent.getExtras();
拡張情報のBundleを取得します。

  if (extras != null) {
    CharSequence ext = extras.getCharSequence(Intent.EXTRA_TEXT);
    if (ext != null) {
      TextView textView1 = (TextView)findViewById(R.id.textView1);
      textView1.setText(ext);
    }
  }
Bundleがnullでなければ、情報が含まれるためgetCharSequence()メソッドを呼び出し情報を取得します。取得した情報をTextViewに表示しします。

実行結果

プロジェクトを実行し端末にアプリケーションをインストールしたのち、Webブラウザを起動し[その他]メニューの[ページの共有]メニューを選択します。


共有できるアプリケーション一覧が表示されるので、今回作成したアプリケーションを選択します。


アプリケーションが起動し、TextViewにWebブラウザで開いていたページのURLが表示されます。

著者
iPentecのプログラマー、最近はAIの積極的な活用にも取り組み中。
とっても恥ずかしがり。
最終更新日: 2024-01-04
作成日: 2012-04-20
iPentec all rights reserverd.