一. Android 12 适配:
PendingIntent 需要添加FLAG_IMMUTABLE或者FLAG_MUTABLE FLAG:推荐FLAG_IMMUTABLE java.lang.IllegalArgumentException: Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent. Strongly consider using FLAG_IMMUTABLE, only use FLAG_MUTABLE if some functionality depends on the PendingIntent being mutable, e.g. if it needs to be used with inline replies or bubbles.
二. installApk 方法中:原方法会取消session } catch (Throwable e) { XLog.e("zxh",
权限:
public static void installApk(Context context, File file) {
XLog.i("zxh", "install InlinedApi slience :" + file.getAbsolutePath()); PackageInstaller.Session session = null; try { PackageInstaller packageInstaller = context.getPackageManager().getPackageInstaller(); packageInstaller.registerSessionCallback(new PackageInstaller.SessionCallback() { @Override public void onCreated(int sessionId) { XLog.e("zxh", "Install Start sessionId-> " + sessionId); } @Override public void onBadgingChanged(int sessionId) { } @Override public void onActiveChanged(int sessionId, boolean active) { } @Override public void onProgressChanged(int sessionId, float progress) { } @Override public void onFinished(int sessionId, boolean success) { if (success) { XLog.e("zxh", "Silent Install Success"); } else { install(context, file); XLog.e("zxh", "Silent Install Fail"); } } }); PackageInstaller.SessionParams params = new PackageInstaller.SessionParams( PackageInstaller.SessionParams.MODE_FULL_INSTALL); int sessionId = packageInstaller.createSession(params); session = packageInstaller.openSession(sessionId); addApkToInstallSession(file, session); // Create an install status receiver. Intent intent = new Intent(); intent.setAction(PACKAGE_INSTALLED_ACTION); //此处也可以使用getBoradcast或者getService回调通知 PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_IMMUTABLE); IntentSender statusReceiver = pendingIntent.getIntentSender(); // Commit the session (this will start the installation workflow). session.commit(statusReceiver); } catch (IOException e) { XLog.e("zxh", "Couldn't install package", e); } catch (RuntimeException e) { XLog.e("zxh", "Couldn't install package", e); if (session != null) { session.abandon(); } } }
private static void addApkToInstallSession(File file, PackageInstaller.Session session) {
long apkFileLength = file.length(); int count; byte[] buffer = new byte[65536]; InputStream inputStream; OutputStream outputStream; try { inputStream = new FileInputStream(file); outputStream = session.openWrite(file.getName(), 0, apkFileLength); while ((count = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, count); } session.fsync(outputStream); inputStream.close(); outputStream.flush(); outputStream.close(); } catch (Throwable e) { XLog.e("zxh", e); } }