コンピュータクワガタ

かっぱのかっぱによるコンピュータ関連のサイトです

Androidアプリ入門 No.52 明示的IntentによるActivityの切り替え

明示的Intent

明示的Intentを用いると任意のActivityを起動できる。画面の切り替え等にも使用することができる。

明示的IntentによるActivityの切り替え

明示的なIntentによるActivityの切り替えのサンプルとして、まずは標準ブラウザを呼び出すサンプルを示す。まず、main.xmlを以下に示す。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <Button
        android:id="@+id/browserButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="browser" />
</LinearLayout>

次に、MainActivity.javaを以下に示す。

package sample.it;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {
    private Button browserButton;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        browserButton = (Button) findViewById(R.id.browserButton);

        browserButton.setOnClickListener(ocl);
    }

    OnClickListener ocl = new OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent();
            intent.setClassName("com.android.browser", "com.android.browser.BrowserActivity");
            startActivity(intent);
        }
    };
}

実行結果は以下、browserボタンを押すと標準のブラウザが起動する。他にブラウザアプリが導入されていてもクラス名まで明示しているため、その他のアプリが起動することはない。