问题
I know we can transfer the data from instant app to the full app using the Storage api of Google Instant as mentioned here.
For devices running OS version less than Oreo, I am trying to read the data as follows:
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);
}
}
But I am getting an error Method threw 'java.io.FileNotFoundException' exception.
Basically when I am trying to read the shared_pref file it is not able to locate it. What is the full name of the file and is there any better way to transfer my shared pref data from instant app to installed app.
回答1:
After spending several hours I was able to make it work but then I found out a much better and easier way to do this. Google also has a cookies api which can be used to share the data from instant app to your full app when user upgrades.
Documentation : 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
I preferred this because it is much cleaner, easy to implement but the most important thing is that you don't have to increase the target sandbox version of your installable app to 2, which is required if you use the Storage API. It works in devices with OS version greater than or equal to 8 as well as with devices with OS version less than 8.
Hope this helps somebody.
来源:https://stackoverflow.com/questions/54132152/how-to-transfer-the-shared-prefs-from-instant-app-to-full-app