I only want to add my own considerations and experiences. I had encountered the same problem.
If you want to get the result the best way is that suggested by Nano and CommonsWare.
I want to highlight that if your apk is internally located you may face the problem "parsing the package error". I want remember you that you need the right permission in the manifest <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
.
But I noticed that is also needed add Intent.FLAG_GRANT_READ_URI_PERMISSION.
So the complete example code could be like this mine:
Uri fileUri = FileProvider.getUriForFile(getApplicationContext(), BuildConfig.APPLICATION_ID + ".provider", currentFile);
Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
intent.setDataAndType(fileUri,"application/vnd.android.package-archive");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.putExtra(Intent.EXTRA_RETURN_RESULT, true);
startActivityForResult(intent, APK_INSTALL_CODE);
Then I would also remember you that this mechanism is all asynchronous, so if you need to know the result to move on, you need to wait it.
I don't know if this is the best way to do but it works:
Uri fileUri = FileProvider.getUriForFile(getApplicationContext(), BuildConfig.APPLICATION_ID + ".provider", currentFile);
Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
intent.setDataAndType(fileUri,"application/vnd.android.package-archive");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true);
intent.putExtra(Intent.EXTRA_RETURN_RESULT, true);
startActivityForResult(intent, APK_INSTALL_CODE);
while (WAIT_APK_INSTALL) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == APK_INSTALL_CODE) {
if (resultCode == 1) {
WAIT_APK_INSTALL = false;
//SUCCESS
}
else {
//FAILED
//maybe it's needed crash the app like me. In my case the installation was necessary
Intent intent = new Intent(getBaseContext(), ErrorActivity.class);
intent.putExtra(GlobalStrings.INTENT_EXTRA_MESSAGE, getString(R.string.apk_installation_failed));
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); // required when starting from Application
startActivity(intent);
System.exit(1); // kill off the crashed app
}
}
}