如何将共享首选项从即时应用转移到完整应用

How to transfer the shared prefs from Instant app to full app

我知道我们可以使用 Google Instant 的存储空间 api 将数据从 Instant 应用程序传输到完整应用程序,如前所述 here

对于运行OS版本低于Oreo的设备,我尝试读取数据如下:

 public void getInstantAppData(final Activity activity, final InstantAppDataListener listener) {
    InstantApps.getInstantAppsClient(activity)
            .getInstantAppData()
            .addOnCompleteListener(new OnCompleteListener<ParcelFileDescriptor>() {
                @Override
                public void onComplete(@NonNull Task<ParcelFileDescriptor> task) {

                    try {
                        FileInputStream inputStream = new FileInputStream(task.getResult().getFileDescriptor());
                        BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
                        ZipInputStream zipInputStream = new ZipInputStream(bufferedInputStream);

                        ZipEntry zipEntry;

                        while ((zipEntry = zipInputStream.getNextEntry()) != null) {
                            Log.i("Instant-app", zipEntry.getName());
                            if (zipEntry.getName().equals("shared_prefs/")) {
                                extractSharedPrefsFromZip(activity, zipEntry);
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
}

private void extractSharedPrefsFromZip(Activity activity, ZipEntry zipEntry) throws IOException {
    File file = new File(activity.getApplicationContext().getFilesDir() + "/shared_prefs.vlp");
    mkdirs(file);
    FileInputStream fis = new FileInputStream(zipEntry.getName());

    BufferedInputStream bis = new BufferedInputStream(fis);
    ZipInputStream stream = new ZipInputStream(bis);
    byte[] buffer = new byte[2048];

    FileOutputStream fos = new FileOutputStream(file);
    BufferedOutputStream bos = new BufferedOutputStream(fos, buffer.length);

    int length;
    while ((length = stream.read(buffer)) > 0) {
        bos.write(buffer, 0, length);
    }
}

但是我收到一个错误 Method threw 'java.io.FileNotFoundException' exception. 基本上,当我尝试读取 shared_pref 文件时,它无法找到它。文件的全名是什么?是否有更好的方法将我的共享首选项数据从免安装应用程序传输到安装的应用程序。

花了几个小时后,我能够让它工作,但后来我发现了一种更好、更简单的方法来做到这一点。 Google 还有一个 cookie api,可用于在用户升级时将数据从免安装应用共享到您的完整应用。

文档:https://developers.google.com/android/reference/com/google/android/gms/instantapps/PackageManagerCompat#setInstantAppCookie(byte%5B%5D)

样本:https://github.com/googlesamples/android-instant-apps/tree/master/cookie-api

我更喜欢这个,因为它更简洁,易于实施,但最重要的是您不必将可安装应用程序的目标沙箱版本增加到 2,如果您使用 Storage API。它适用于 OS 版本大于或等于 8 的设备以及 OS 版本小于 8 的设备。

希望这对某人有所帮助。