创建两个活动,第一个活动名为FirstActivity,第二个活动为SecondActivity,在第一个活动的View界面创建按钮,id为button_1。
显示启动:
Button button1 = (Button) findViewById(R.id.button_1);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(FirstActivity.this, "You clicked Button 1", Toast.LENGTH_SHORT).show();
//显式
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
startActivity(intent);
}
});
隐式启动:
通过在AndroidManifest.xml中的<activity>标签下配置<intent-filter>内容,可以指定当前活动能够响应的action,category,以及data。如下述代码:
<action android:name="com.example.activitytest.ACTION_START" />
//默认的category,调用startActivity时会自动添加至Intent
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.MY_CATEGORY" />
在<action>标签中我们指明了当前活动可以响应com.example.activitytest.ACTION_START这个action,而<category>标签则包含了一些附加信息。只有<action>和<category>中的内容能够匹配Intent中的action和category时,这个活动才能响应该Intent。
所以FirstActivity中的按钮点击事件,代码如下:
Button button1 = (Button) findViewById(R.id.button_1);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("com.example.activitytest.ACTION_START");
intent.addCategory("android.intent.category.MY_CATEGORY");
startActivity(intent);
}
});
<data>标签用于更精确的指定当前活动能响应什么类型的数据。主要配置以下的内容。
android:scheme 用于指定数据的协议部分。
android:host 用于指定数据的主机部分。
android:port 用于指定数据的端口部分。
android:path 用于指定主机名和端口之后的部分。
android:minmeType 用于指定可以处理的数据类型。
不过一般在<data>标签中不会指定过多的内容,入只需要指定android:scheme为http,就可以响应所有的http协议的intent了。当然也可以设置geo表示显示地理位置,设置tel表示拨打电话。下面代码展示如何在程序中调用系统的拨号界面(http,geo同理):
Button button1 = (Button) findViewById(R.id.button_1);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(FirstActivity.this, "You clicked Button 1", Toast.LENGTH_SHORT).show();
//使用浏览器访问网址
/*Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("http://www.baidu.com"));*/
//拨打电话
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:10086"));
startActivity(intent);
});
}