Android学习之路-Activity传递数据(9)

Intent使用Bundle对象存放待传递的数据信息

Bundle对象操作各类型数据的读写方法说明见下表:

 一、在活动之间传递消息

1.1向下一个Activity发送数据

    @Override
    public void onClick(View v) {
        Intent intent = new Intent(ActSendActivity.this, ActReceiveActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("request_time", DateUtil.getNowTime());
        bundle.putString("request_content", tv_send.getText().toString());
        intent.putExtras(bundle);
        startActivity(intent);
    }
public class ActReceiveActivity extends AppCompatActivity {
    private TextView tv_receive;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_act_receive);
        tv_receive = findViewById(R.id.tv_receive);
        Bundle bundle = getIntent().getExtras();
        String request_time = bundle.getString("request_time");
        String request_content = bundle.getString("request_content");
        String desc = String.format("收到的请求时间为:\n %s,\n 请求内容为:\n %s",request_time,request_content);
        tv_receive.setText(desc);
    }
}

 1.2、向上一个Activity返回数据

package com.qidian.chapter04;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import com.qidian.chapter04.utils.DateUtil;

public class ActRequestActivity extends AppCompatActivity implements View.OnClickListener {
    private  TextView tv_request;
    private  TextView tv_response;
    private  String myRequest = "你睡了吗?来我家";
    private ActivityResultLauncher<Intent> register;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_act_request);
        tv_request = findViewById(R.id.tv_request);
        tv_request.setText(myRequest);
        findViewById(R.id.btn_request).setOnClickListener(this);
        register = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                if (result != null) {
                    Intent intent = result.getData();
                    if (intent != null && result.getResultCode() == Activity.RESULT_OK) {
                        Bundle bundle = intent.getExtras();
                        String request_content = bundle.getString("request_content");
                        String desc = String.format("收到的消息为:\n%s",request_content);
                        tv_response.setText(desc);
                    }
                }
            }
        });

        tv_response = findViewById(R.id.tv_response);
        tv_response.setText("待返回的消息为:" );
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent(ActRequestActivity.this, ActResponseActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("request_time", DateUtil.getNowTime());
        bundle.putString("request_content", myRequest);
        intent.putExtras(bundle);
        register.launch(intent);
    }
}
package com.qidian.chapter04;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import com.qidian.chapter04.utils.DateUtil;

public class ActResponseActivity extends AppCompatActivity implements View.OnClickListener {
    private  final  String myResponse = "还没睡";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_act_response);
        TextView tv_response = findViewById(R.id.tv_response);
        Bundle bundle = getIntent().getExtras();
        String request_time = bundle.getString("request_time");
        String request_content = bundle.getString("request_content");
        String desc = String.format("收到的请求:\n %s",request_content);
        tv_response.setText(desc);
        findViewById(R.id.btn_response).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putString("response_time", DateUtil.getNowTime());
        bundle.putString("request_content", myResponse);
        intent.putExtras(bundle);
        // 携带意图返回上一个页面,RESULT_OK 表示处理成功
        setResult(Activity.RESULT_OK,intent);
        // 结束当前活动
        finish();
    }
}

二、为活动补充附加信息

3.1、利用资源文件strings.xml配置字符串

public class ReadStringActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_read_string);
        TextView tv_resource = findViewById(R.id.tv_resource);
        // 从strings.xml文件获取weather_str的字符串的值(为什么要把这些字符串放在xml文件呢?因为配置文件strings.xml文件是不需要进行编译的可以随时改,java代码一旦修改需要重新编译)
        String value = getString(R.string.weather_str);
        tv_resource.setText(value);
    }
}

3.2、利用元数据传递配置信息

使用场景:在使用第三方那个SDK时需要进行相关的类似token之类的验证,需要将SDK提供的Activity引入manifest.xml文件并正确配置<meta-data android:name="token" android:value="xxx"></meta-data>

  <activity
            android:name=".MetaDataActivity"
            android:exported="true"
            android:launchMode="standard"
            tools:ignore="DuplicateActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <meta-data android:name="weather_str" android:value="晴天"></meta-data>
        </activity>
 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_meta_data);
        TextView tv_meta = findViewById(R.id.tv_meta);
        // 获取应用包管理器
        PackageManager packageManager = getPackageManager();
        try {
            // 从应用包管理器中获取的活动信息
            ActivityInfo info = packageManager.getActivityInfo(getComponentName(), packageManager.GET_META_DATA);
            // 获取活动附加的元数据信息
            Bundle bundle = info.metaData;
            String weather = bundle.getString("weather_str");
            tv_meta.setText(weather);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }

 

3.3、给应用页面注册快捷方式

元数据不仅能传递简单的字符串参数,还能传送更复杂的资源数据,比如支付宝的快捷方式菜单Android7.0之后支持(温馨提示:shortcutShortLabel、shortcutLongLabel)

<?xml version="1.0" encoding="utf-8"?>
<shortcuts xmlns:android="http://schemas.android.com/apk/res/android">
    <shortcut
        android:enabled="true"
        android:icon="@mipmap/ic_launcher"
        android:shortcutId="first"
        android:shortcutShortLabel="@string/first_long"
        android:shortcutLongLabel="@string/first_long">
        <intent android:action="android.intent.action.VIEW"
            android:targetPackage="com.guo.chapter4"
            android:targetClass="com.guo.chapter4.ActStartActivity"/>
        <categories android:name="android.shortcut.conversation" />
    </shortcut>
    <shortcut
        android:enabled="true"
        android:icon="@mipmap/ic_launcher"
        android:shortcutId="second"
        android:shortcutShortLabel="@string/second_long"
        android:shortcutLongLabel="@string/second_long">
        <intent android:action="android.intent.action.VIEW"
            android:targetPackage="com.guo.chapter4"
            android:targetClass="com.guo.chapter4.JumpFirstActivity"/>
        <categories android:name="android.shortcut.conversation" />
    </shortcut>
    <shortcut
        android:enabled="true"
        android:icon="@mipmap/ic_launcher"
        android:shortcutId="third"
        android:shortcutShortLabel="@string/third_long"
        android:shortcutLongLabel="@string/third_long">
        <intent android:action="android.intent.action.VIEW"
            android:targetPackage="com.guo.chapter4"
            android:targetClass="com.guo.chapter4.LoginInputActivity"/>
        <categories android:name="android.shortcut.conversation" />
    </shortcut>
</shortcuts>

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值