【发布时间】:2019-01-10 15:42:16
【问题描述】:
我知道我们可以使用 Google Instant 的 Storage api 将数据从免安装应用传输到完整应用,如 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. 基本上当我试图读取 shared_pref 文件时它无法找到它。文件的全名是什么?有没有更好的方法将我的共享首选项数据从即时应用程序传输到已安装的应用程序。
【问题讨论】:
-
文件的全名是您在使用Context.getSharedPreferences 创建文件时选择的名称。我不确定,但我认为您的代码可能正在尝试读取目录 ZipEntry。在检测到目录之后和
extractSharedPrefsFromZip之前尝试移动到下一个条目,如果它不起作用,您可以发布异常的完整堆栈跟踪吗? -
见stackoverflow.com/a/45315101/6668797,如果只是共享首选项,使用cookie api会更容易,但如果你打算使用ZIP方法,我稍后会仔细研究。
标签: android zip android-instant-apps