SystemAPP silent installation

register listener

<receiver
    android:name="InstallResultReceiver"
    android:enabled="true"
    android:exported="true">
    <intent-filter>
        <action android:name="android.content.pm.extra.STATUS"/>
    </intent-filter>

</receiver>

public class InstallResultReceiver extends BroadcastReceiver {
    public final String TAG = "carden" + InstallResultReceiver.class.getSimpleName();

    public InstallResultReceiver() {
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d(TAG, "Received installation feedback broadcast");
        if (intent != null) {
            final int status = intent.getIntExtra(PackageInstaller.EXTRA_STATUS,
                    PackageInstaller.STATUS_FAILURE);
            Log.d(TAG, "Received installation feedback broadcast --"+status);
            if (status == PackageInstaller.STATUS_SUCCESS) {
                // success
                int requestCode=intent.getIntExtra("flag",0);
                if (requestCode==1){
                    Log.d(TAG,"Silent installation succeeded");
                }else if (requestCode==2){
                    Log.d(TAG,"Silent uninstallation succeeded");
                }
                Log.d(TAG, "APP Install Success!");
            } else {
                String msg = intent.getStringExtra(PackageInstaller.EXTRA_STATUS_MESSAGE);
                Log.e(TAG, "Install FAILURE status_massage" + msg);
            }
        }

    }
}

2. Installation, the path is dynamically filled in according to your own authorization, I wrote it to death

private void silentInstallApk(Context context,String apkFilePath, String apkName) {
    File apkFile = new File(apkFilePath);
    long apkFileLength = apkFile.length();
    PackageManager pm = context.getPackageManager();
    PackageInstaller packageInstaller = pm.getPackageInstaller();
    packageInstaller.registerSessionCallback(new PackageInstaller.SessionCallback() {
        @Override
        public void onCreated(int sessionId) {
            Log.e(TAG, "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) {
                Log.e(TAG, "Silent Install Success");
            } else {
                Log.e(TAG, "Silent Install Fail");
            }
        }
    });

    int count;
    int sessionId;
    byte[] buffer = new byte[1024*1024];

    InputStream inputStream;
    OutputStream outputStream;
    PackageInstaller.Session session = null;
    PackageInstaller.SessionParams sessionParams;

    try {
        sessionParams = new PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL);
        sessionId =  packageInstaller.createSession(sessionParams);
        session = packageInstaller.openSession(sessionId);
        Log.e(TAG, "Install Start sessionId-> " + sessionId);
        inputStream = new FileInputStream(apkFile);
        outputStream = session.openWrite("base.apk", 0, apkFileLength);

        while((count = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, count);
            float progress = ((float)count / (float)apkFileLength);
            session.setStagingProgress(progress);
        }
        session.fsync(outputStream);

        inputStream.close();
        outputStream.flush();
        outputStream.close();

        Intent intent = new Intent(this, InstallResultReceiver.class);
        intent.putExtra("flag", 1);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this,
                1, intent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        session.commit(pendingIntent.getIntentSender());
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (session != null) {
            session.close();
        }
    }
}

int mSessionId =-1;

public String installApp(String apkFilePath) {
    String success = "fail";
    Log.d(TAG, "installApp()------->" + apkFilePath);
    File apkFile = new File(apkFilePath);
    if (!apkFile.exists()) {
        Log.d(TAG, "The file does not exist");

    }

    PackageInfo packageInfo = getPackageManager().getPackageArchiveInfo(apkFilePath, PackageManager.GET_ACTIVITIES | PackageManager.GET_SERVICES);
    if (packageInfo != null) {
        String packageName = packageInfo.packageName;
        int versionCode = packageInfo.versionCode;
        String versionName = packageInfo.versionName;
        Log.d("ApkActivity", "packageName=" + packageName + ", versionCode=" + versionCode + ", versionName=" + versionName);
    }

    PackageInstaller packageInstaller = getPackageManager().getPackageInstaller();
    PackageInstaller.SessionParams sessionParams
            = new PackageInstaller.SessionParams(PackageInstaller
            .SessionParams.MODE_FULL_INSTALL);
    Log.d(TAG, "apkFile length" + apkFile.length());
    sessionParams.setSize(apkFile.length());

    try {
        mSessionId = packageInstaller.createSession(sessionParams);
    } catch (IOException e) {
        e.printStackTrace();
    }

    Log.d(TAG, "sessionId---->" + mSessionId);
    if (mSessionId != -1) {
        boolean copySuccess = onTransfesApkFile(apkFilePath);
        Log.d(TAG, "copySuccess---->" + copySuccess);
        if (copySuccess) {
            boolean isSuccess = execInstallAPP();
            success = isSuccess ? "Success" : "fail";
            Log.d(TAG, "Silent Success---" + isSuccess);
        }

    }
    return success;
}
private boolean onTransfesApkFile(String apkFilePath) {
    Log.d(TAG, "---------->onTransfesApkFile()<---------------------");
    InputStream in = null;
    OutputStream out = null;
    PackageInstaller.Session session = null;
    boolean success = false;
    try {
        File apkFile = new File(apkFilePath);
        session = getPackageManager().getPackageInstaller().openSession(mSessionId);
        out = session.openWrite("base.apk", 0, apkFile.length());
        in = new FileInputStream(apkFile);
        int total = 0, c;
        byte[] buffer = new byte[1024 * 1024];
        while ((c = in.read(buffer)) != -1) {
            total += c;
            out.write(buffer, 0, c);
        }
        session.fsync(out);
        Log.d(TAG, "streamed " + total + " bytes");
        success = true;
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (null != session) {
            session.close();
        }
        try {
            if (null != out) {
                out.close();
            }
            if (null != in) {
                in.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return success;
}


private boolean execInstallAPP() {
    Log.d(TAG, "--------------------->execInstallAPP()<------------------");
    PackageInstaller.Session session = null;
    try {
        session = getPackageManager().getPackageInstaller().openSession(mSessionId);
        Intent intent = new Intent(this, InstallResultReceiver.class);
        intent.putExtra("flag", 1);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this,
                1, intent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        session.commit(pendingIntent.getIntentSender());
        return true;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } finally {
        if (null != session) {
            session.close();
        }
    }
}

Guess you like

Origin blog.csdn.net/Angle_Byron/article/details/130511683