Android_Intent之活动切换和数据传输

Android_Intent之活动切换和数据传输

一、Intent的活动切换

1、显示切换:

通过实例化Intent对象时为其传入当前所在活动要转的活动,然后调用startActivity(Intent intent)进行切换

Intent intent=new Intent(FirstActivity.this,SecendActivity.class);
startActivity(intent);

2、隐式切换:

基本思想是通过条件匹配来选择哪一个活动可以成为Intent转换的对象
步骤:
1、在AndroidManifest.xml中为目的活动页面添加

		<activity
            android:name=".SecendActivity"
            android:label="This is SecondActivity">
            <intent-filter>
                <action android:name="com.wang.activity.ACTION_START" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>

2、在当前活动需要跳转的地方进行跳转

Intent intent=new Intent("com.wang.activity.ACTION_START");
startActivity(intent);

注意:
①隐式调用中属性可以有多个,且每个属性都要在当前活动(准备跳转)显示指明,指明方式是在startActivity前添加intent.addCategory(String string)函数,形参string为category属性的值。
②隐式调用时必须action和category两个属性都要匹配,但这里代码没有对category进行约束,是因为category属性值为DEFAULT,系统自动添加。

3、不同应用之间切换

例如从当前活动页面转到浏览器

Intent intent=new Intent("Intent.ACTION_VIEW", Uri.parse("http://www.baidu.com"));
startActivity(intent);

说明:
①"Intent.ACTION_VIEW"是内置动作属性值,相当于“android.intent.action.VIEW”,自我感觉像是宏定义
②第二个参数是Uri对象,Uri.parse()将传入的域名转化为Uri对象。

4、传数据

1、向下一个活动传数据
步骤:
①在当前活动待跳转的地方添加如下代码

Intent intent=new Intent(FirstActivity.this,SecendActivity.class);
//将值添加到intent中
intent.putExtra("key_data","Super man");//键值对的形式,第一个参数为键值,后一个为参数
startActivity(intent);

②在下一个活动需要数据的地方接收数据

Intent intent1=getIntent();//接收到上级的Intent对象
String str=intent1.getStringExtra("key_data");//此时str的值为"Super man",

2、向上一个活动返回数据
步骤:
①在当前活动待跳转的地方添加如下代码

Intent intent=new Intent(FirstActivity.this,SecendActivity.class);
//开始跳转并期待跳转后的页面被销毁后会返回参数
startActivityForResult(intent,1);//第二个参数为请求编号
//重写销毁后返回获得数据的方法
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode)//一个活动中会有不止一个地方需要返回数据,通过requestCode区分
        {
            case 1:
                if(resultCode==RESULT_OK)
                {
                    Log.d("FirstActivity", data.getStringExtra("result_data"));
                }
                break;
            default:
        }
    }

②在下一个活动提供数据的地方添加

Intent intent=new Intent();
intent.putExtra("result_data","super man");
setResult(RESULT_OK,intent);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值