You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android技术问询:如何将URI转为Intent及开机恢复存储的Intent数据

解决方案说明

一、URI 转换为 Intent 的正确方式

你提到的 Intent.parseUri() 其实是正确的方向,但要注意几个关键细节:

  • 确保传入的 URI 符合 Intent 规范(比如带 intent:// 协议的标准 Intent URI,或是合法的 content URI)
  • 第二个参数的 flag 可按需选择,比如 Intent.URI_ALLOW_UNSAFE 允许非安全 URI,用 0 则遵循默认解析规则

给你一个可直接参考的示例:

// 假设这是一个合法的 Intent URI
String intentUri = "intent://com.example.target#Intent;action=com.example.ACTION_TEST;S.extra_msg=demo;end";
try {
    Intent targetIntent = Intent.parseUri(intentUri, Intent.URI_ALLOW_UNSAFE);
    // 后续可使用该 Intent,比如启动对应 Activity
    startActivity(targetIntent);
} catch (URISyntaxException e) {
    e.printStackTrace();
    // 处理 URI 格式错误的异常
}

二、Intent 与 ResultCode 的持久化存储与恢复问题

你当前的代码里直接用 String.valueOf(resultData) 把 Intent 转成字符串存储是错误的——这种方式只会得到 Intent 对象的 toString() 输出,并不是可反序列化的有效数据,所以后续用 Intent.parseUri() 必然解析失败。

正确的做法是利用 Intent 实现的 Parcelable 接口,将其序列化为字节数组后再存储到 SharedPreferences 中:

1. 存储逻辑修改

public static int resultCode;
public static Intent resultData;

// 将 Intent 序列化为字节数组
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
    Parcel parcel = Parcel.obtain();
    resultData.writeToParcel(parcel, 0);
    parcel.writeToStream(bos);
    parcel.recycle();
} catch (IOException e) {
    e.printStackTrace();
}
byte[] intentBytes = bos.toByteArray();

// 写入 SharedPreferences
SharedPreferences.Editor editor1 = getSharedPreferences("YourPrefsName", MODE_PRIVATE).edit();
editor1.putInt("code", resultCode);
// 用 Base64 编码字节数组为字符串,避免存储乱码
editor1.putString("data123", Base64.encodeToString(intentBytes, Base64.DEFAULT));
editor1.apply();

2. 开机广播接收器中恢复 Intent 的代码

private Intent telApp;
SharedPreferences sharedPreferences = getSharedPreferences("YourPrefsName", MODE_PRIVATE);
int code = sharedPreferences.getInt("code", 0);
String intentBase64 = sharedPreferences.getString("data123", null);

if (intentBase64 != null) {
    try {
        // 解码并反序列化为 Intent
        byte[] intentBytes = Base64.decode(intentBase64, Base64.DEFAULT);
        ByteArrayInputStream bis = new ByteArrayInputStream(intentBytes);
        Parcel parcel = Parcel.obtain();
        parcel.readFromStream(bis);
        parcel.setDataPosition(0); // 重置指针到起始位置
        telApp = Intent.CREATOR.createFromParcel(parcel);
        parcel.recycle();
        
        Log.e("data...", "恢复的 Intent: " + telApp.toString());
        // 这里即可正常使用恢复后的 Intent 和 resultCode
    } catch (IOException e) {
        e.printStackTrace();
        // 处理反序列化失败的异常
    }
}

额外注意事项

  • 要保证 Intent 携带的所有额外数据(Extras)都是基本类型、可序列化类型,或是实现了 Parcelable 的自定义类,否则序列化会失败
  • 开机广播接收器中获取 SharedPreferences 时,建议使用 getApplicationContext(),避免因上下文持有导致内存泄漏
  • 如果恢复后的 Intent 用于启动 Activity,要注意权限问题,比如某些隐式 Intent 需在 AndroidManifest 中声明对应权限

内容的提问来源于stack exchange,提问作者kra.rd.test

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:42:45