I am trying to install programmatically from my downloads folder updates of the application within an AsyncTask.
final String PACKAGE_INSTALLED_ACTION = "com.example.android.apis.content.SESSION_API_PACKAGE_INSTALLED";
PackageInstaller.Session session = null;
try {
PackageInstaller packageInstaller = ContextHolder.getInstance().getContext().getPackageManager().getPackageInstaller();
PackageInstaller.SessionParams params = new PackageInstaller.SessionParams(
PackageInstaller.SessionParams.MODE_FULL_INSTALL);
int sessionId = packageInstaller.createSession(params);
session = packageInstaller.openSession(sessionId);
addApkToInstallSession(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/" + fileName,
session); // !!! Here it's crashing
Context context = ContextHolder.getInstance().getContext();
Intent intent = new Intent(context, Login.class);
intent.setAction(PACKAGE_INSTALLED_ACTION);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
IntentSender statusReceiver = pendingIntent.getIntentSender();
session.commit(statusReceiver);
session.close();
Here's the addApkToInstallSession function:
private void addApkToInstallSession(String assetName, PackageInstaller.Session session)
throws IOException {
try (OutputStream packageInSession = session.openWrite("package", 0, -1);
InputStream is = ContextHolder.getInstance().getContext().getAssets().open(assetName)) {
byte[] buffer = new byte[16384];
int n;
while ((n = is.read(buffer)) >= 0) {
packageInSession.write(buffer, 0, n);
}
}
}
I'm getting this error message even thiugh I checked and this file exists:
java.io.FileNotFoundException: /storage/emulated/0/Download/app-debug-2.apk
Edit 1: It's important to note that I'm currently working with SDK 30
Edit 2: I've noticed I was trying to accest something that didn't exist in the Assets folder, that's the reason it was crashing.
The code of the function addApkToInstallSession() looks now like this - without any errors:
private void addApkToInstallSession(String assetName, PackageInstaller.Session session)
throws IOException {
try (OutputStream outputStream = session.openWrite("package", 0, -1);
InputStream is = new BufferedInputStream(new FileInputStream(assetName))) {
byte[] buffer = new byte[65536];
int n;
while ((n = is.read(buffer)) >= 0) {
outputStream.write(buffer, 0, n);
}
}
}
Now, however, it fails to do anything. It just runs, without crashing, but also without updtating the app...
Edit 3 Parts of the code were copied from: https://android.googlesource.com/platform/development/+/master/samples/ApiDemos/src/com/example/android/apis/content/InstallApkSessionApi.java P.S. I'm pretty new on StackOverflow so don't be too harsh on me ;)