インテントとは、アプリケーションから、新しいアクティビティを起動するためのパラメータです。
起動するアクティビティは、同じアプリケーション内のアクティビティでも、他のアプリケーション内のアクティビティでも指定することができます。他のアプリケーションのアクティビティを指定するためには、アクションと、Uriという二つのパラメータを指定します。Androidでは、あらかじめ規定されたインテントにたいする動作が組み込まれています。
ここでは、代表的なアクションである、ACTION_VIEWに対する動作を確認するためのアプリケーションを作成してみましょう。
必要に応じて、File > New > Android Projectで新規のプロジェクトを作成します。
ここでは、以下のようなプロジェクトを作成してみます。
Project Name | HelloIntentProject |
Build Target | Google APIs |
Application Name | HelloIntent |
Package Name | jp.hews.hellointent |
Create Activity | HelloIntentActivity |
Min SDK Version | 3(Bild Targetを指定すると自動的に設定される) |
画面にボタンを配置するには、レイアウトを定義したXMLファイルを編集します。
まず、レイアウトを定義したres/layout/main.xmlを開いて、画面上にボタンを配置します。
この画面でボタンを配置するには、GUIで挿入する方法と、下部の「main.xml」タブから直接XMLを編集する方法があります。ここでは、GUIを用いて定義します。
EditTextから文字列を取り出して、ACTION_VIEWのインテントを作成して、startActivityを呼び出します。
判定できないURIの場合には、エラーの内容をテキストビューに表示します。
以下のメソッドをHelloIntentActivity.javaに定義してみましょう。
private void sendIntent() { try { EditText et = (EditText)findViewById(R.id.EditText01); Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(et.getText().toString())); startActivity(i); } catch (Exception e) { TextView t = (TextView)findViewById(R.id.TextView01); t.setText(e.toString()); } }
ボタンが押された時に、定義したsendIntentを呼び出すリスナーを登録します。
public class HelloIntentActivity extends Activity implements View.OnClickListener { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button button = (Button)findViewById(R.id.Button01); button.setOnClickListener(this); } public void onClick(View arg0) { sendIntent(); }
URIを入力して、あらかじめ組み込まれているUriに対応するアクティビティを起動してみます。
Uri | 動作 | 例 |
http://web_address | ブラウザを起動する | http://www.google.com/ |
tel:phone_number | ダイヤル画面を表示します | tel:123456 |
geo:latitude,longitude | 地図を表示します | geo:37,137 |
content://contacts/people | コンタクトリストを表示します | content://contacts/people/1 |
package jp.hews.hellointent; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class HelloIntentActivity extends Activity implements View.OnClickListener { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button button = (Button)findViewById(R.id.Button01); button.setOnClickListener(this); } public void onClick(View arg0) { sendIntent(); } private void sendIntent() { try { EditText et = (EditText)findViewById(R.id.EditText01); Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(et.getText().toString())); startActivity(i); } catch (Exception e) { TextView t = (TextView)findViewById(R.id.TextView01); t.setText(e.toString()); } } }