在Android中将Bundle数据保存到文件中并从文件中读取



我正在处理的web应用程序有webviews..有3或4个webview..我需要的是我想从以前的统计用户杀死应用程序后恢复这些webviews ..我可以像这样保存webviewstate

Bundle bundle = new Bundle();    
WebView.saveState(Bundle);

这些是我的要求…

  1. 将每个bundle数据保存到外部存储位置(自定义创建的文件夹)分开
  2. 单独读取保存的数据并转换为bundle,然后恢复webviews启动应用程序

我在网上搜到了这个

  1. 用于在缓存文件夹中单独保存bundle数据——>"webstack"文件夹中,

    public void save(){File stackpath = new File(getContext().getExternalCacheDir(), "webstack"+unique_tab_id);

    Bundle bundle = new Bundle();
    WebBackForwardList stacks = saveState(bundle);
    if(stacks!=null&&stacks.getSize()>0) {
    Parcel parcel = Parcel.obtain();
    parcel.setDataPosition(0);
    bundle.writeToParcel(parcel, 0);
    byte[] bytes = parcel.marshall();
    parcel.recycle();
    ...//save Byte Array Data to file
    } else {
    stackpath.delete();
    }
    

}

  1. 这是用于读取保存的数据并单独恢复bundle,

    public void Boolean restore(){File stackpath = new File(getContext().getExternalCacheDir(), "webstack"+unique_tab_id);

    if(stackpath.exists()) {
    Parcel parcel = Parcel.obtain();
    byte[] data = ...//read file as Byte Array
    parcel.unmarshall(data, 0, data.length); 
    parcel.setDataPosition(0);
    Bundle bundle = new Bundle();
    bundle.readFromParcel(parcel);
    parcel.recycle();
    WebBackForwardList stacks = restoreState(bundle);
    if(stacks!=null && stacks.getSize()>0) {
    return true;
    }
    }
    return false;
    

    }

但是这不起作用,我看不到任何名为"webstack"的文件夹。在缓存目录中,没有保存的数据。此外,我有一个想法,将webview状态保存为访问过的url列表在aquite数据库中,但这不是合适的方式,甚至它是一个混乱…

请帮帮我…对不起,我的英语不好。

Thanks in Advance.

对于bundle,我建议先将bundle转换为HashMap<String,*>然后你可以把它存储到一个文件中。读取过程类似。您需要将file解析为HashMap,并将键值对设置为new bundle。Bundle是二进制格式,可以包含可打包的对象和另一个Bundle,因此在应用程序外序列化和反序列化不可能没有错误。还要注意,bundle可以有不同的版本,因此不能从一个应用程序转移到另一个应用程序。

最新更新