代码之家  ›  专栏  ›  技术社区  ›  Ezio

如何将共享的首选项从即时应用程序传输到完整应用程序

  •  2
  • Ezio  · 技术社区  · 6 年前

    我知道我们可以使用上面提到的Google Instant的存储API将数据从Instant应用程序传输到完整的应用程序。 here .

    对于运行低于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. 基本上,当我试图读取共享的_pref文件时,它找不到它。文件的全名是什么?有没有更好的方法可以将我共享的pref数据从即时应用程序传输到已安装的应用程序。

    1 回复  |  直到 6 年前
        1
  •  0
  •   Ezio    6 年前

    在花了几个小时之后,我能够让它工作起来,但后来我发现了一种更好更容易的方法。谷歌还拥有一个cookies API,可以在用户升级时将数据从即时应用程序共享到您的完整应用程序。

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

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

    我更喜欢这个,因为它更干净,易于实现,但最重要的是,您不必将可安装应用程序的目标沙盒版本增加到2,如果使用存储API,这是必需的。它适用于操作系统版本大于或等于8的设备,以及操作系统版本小于8的设备。

    希望这能帮助别人。