Intent大致分为显示和隐式。
Intent是Android程序中各组件之间进行交互的一种重要方式,它不仅可以指明当前足尖想要执行的动作,还可以在不同组件之间传递数据。Intent一般可被用于启动活动,启动服务以及发送广播等场景。
显示Intent:意图非常明确
创建第二个活动Second_Activity内容保持不变,布局文件命名为second_layout
内容为:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SecondActivity">
<Button
android:id="@+id/Button_2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button 2" />
</LinearLayout>
非主活动不用配置<intent-fliter>
@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);
<!-- FirstActivity.this作为上下文,传入SecondActivity.class作为目标活动 -->
startActivity(intent);<!—用来执行-->
}
隐式Intent:不明确指出想要启动哪个活动
<activity android:name=".SecondActivity">
<intent-filter>
<action android:name="com.example.activitytest.ACTION_START"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first_layout);
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("om.example.activitytest.ACTION_START");
startActivity(intent);
}
});
增加一个category:
在firstActivity中onClick添加
intent.addCategory("com.example.activitytest.MY_CATEGORY");
在<intent-filter>中创建一个category声明:
<category android:name="com.example.activitytest.MY_CATEGORY"/>
打开网页
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_layout);
Button button2 = (Button)findViewById(R.id.Button_2);
button2.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("http://wwww.baidu.com"));
startActivity(intent);
}
});
}
<!-- Intent.ACTION_VIEW 是系统内置动作,其常量为android.intent.action.VIEW。
通过Uri.parse方法,将一个网址字符串解析成一个Uri对象,再调用Intent的setData()方法将这个对象传递进去-->
创建第三个活动来响应网页的intent
在注册文件中声明
<activity android:name=".thirdActivity">
<intent-filter>
<action android:name="android.intent.ation.VIEW"/>
<category android:name="android.intent.cagecory.DEFAULT"/>
<data android:scheme="http"/>
</intent-filter>
</activity>