欢迎各位 阿弥陀佛转载本博客文章,转载请注明来源
通过5个button演示Intent的5种典型使用:
布局源码:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/button_1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="显式调用" />
<Button
android:id="@+id/button_2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="隐式调用" />
<Button
android:id="@+id/button_3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="隐式调用外部" />
<Button
android:id="@+id/button_4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="传递数据" />
<Button
android:id="@+id/button_5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="数据返回" />
</LinearLayout>
1.Intent的显式使用:
Intent intent=new Intent(FirstActivity.this,SecondActivity.class);
startActivity(intent);
2. Intent的隐式使用,打开Manifest属性如下的活动:
<intent-filter>
<action android:name="com.example.activitytest.ACTION_START" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
Intent intent1=new Intent("com.example.activitytest.ACTION_START");
startActivity(intent1);
3. 打开有<action android:name="android.intent.action.VIEW" />的活动或者 外部浏览器:
Intent intent2 = new Intent(Intent.ACTION_VIEW);
intent2.setData(Uri.parse("http://www.baidu.com"));
startActivity(intent2);
4.打开第2个活动并传递一个字符串:
Intent intent3 = new Intent(FirstActivity.this, SecondActivity.class);
String str="hao";
intent3.putExtra("extra_data",str);
startActivity(intent3);
5. 打开有返回的 活动:
Intent intent4 = new Intent(FirstActivity.this, SecondActivity.class);
startActivityForResult(intent4, 1);
接收代码:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 1:
if (resultCode == RESULT_OK) {
String returnedData = data.getStringExtra("data_return");
Toast.makeText(getApplicationContext(), returnedData,
Toast.LENGTH_SHORT).show();
}
break;
default:
}
}
第2页的跳回按钮:
Intent intent = new Intent();
intent.putExtra("data_return", "Hello FirstActivity");
setResult(RESULT_OK, intent);
finish();
源码免费下载链接:https://download.csdn.net/download/nmgsyps2017/20351695