2.4使用Intent在活动之间穿梭
Intent是Android程序中各组件之间进行交互的一种重要方式,它不仅可以指明当前组件想要执行的动作,还可以在不同组件之间传递数据。Intent一般用于启动活动、启动服务以及发送广播等场景。
使用显式Intent
1、新建活动名为SecondActivity,自动创建布局second_layout。
2、使用LinearLayout布局,从first_layout粘贴。
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/button_2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="打开第三个活动"
/>
3、从FirstActivity到SecondActivity。
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);
}
});
使用隐式Intent
隐式Intent不明确指出我们想要启动哪一个活动,而是指定一系列更为抽象的action和category等信息,然后交由系统去分析这个Intent,并帮我们找出合适的活动去启动。
1、新建活动名为ThirdActivity,自动创建布局third_layout。
2、使用LinearLayout布局,从first_layout粘贴。
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/button_3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="关闭当前活动"/>
3、在AndroidManifest.xml中指定当前活动能响应的action和category。
<activity android:name=".ThirdActivity">
<intent-filter>
<action android:name="com.example.activitytest.ACTION_START" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
4、从活动SecondActivity到活动ThirdActivity.
button2.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
Intent intent=new Intent("com.example.activitytest.ACTION_START");
startActivity(intent);
}
});
第一次看程序的崩溃
每个Intent中只能指定一个action,但却能指定多个category。
5、在button2中加入category。
button2.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
Intent intent=new Intent("com.example.activitytest.ACTION_START");
intent.addCategory("com.example.activitytest.MY_CATEGORY");
startActivity(intent);
}
});
运行后APP崩溃如下图
在logcat界面查看错误日志
Process: com.example.activitytest, PID: 8315
android.content.ActivityNotFoundException: No Activity found to handle Intent { act=com.example.activitytest.ACTION_START cat=[com.example.activitytest.MY_CATEGORY] }
错误信息中提醒我们,没有任何一个活动可以响应我们的Intent。在AndroidManifest.xml配置文件中加入
<activity android:name=".ThirdActivity">
<intent-filter>
<action android:name="com.example.activitytest.ACTION_START" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="com.example.activitytest.MY_CATEGORY" />
</intent-filter>
</activity>
注销一个活动finish
button3.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
finish();
}
});