Example usage for android.content.pm PackageInstaller openSession

List of usage examples for android.content.pm PackageInstaller openSession

Introduction

In this page you can find the example usage for android.content.pm PackageInstaller openSession.

Prototype

public @NonNull Session openSession(int sessionId) throws IOException 

Source Link

Document

Open an existing session to actively perform work.

Usage

From source file:Main.java

public static boolean installPackage(Context context, InputStream in, String packageName) throws IOException {
    PackageInstaller packageInstaller = context.getPackageManager().getPackageInstaller();
    PackageInstaller.SessionParams params = new PackageInstaller.SessionParams(
            PackageInstaller.SessionParams.MODE_FULL_INSTALL);
    params.setAppPackageName(packageName);
    // set params
    int sessionId = packageInstaller.createSession(params);
    PackageInstaller.Session session = packageInstaller.openSession(sessionId);
    OutputStream out = session.openWrite("COSU", 0, -1);
    byte[] buffer = new byte[65536];
    int c;/*  w  w  w .j  av  a 2s  . c  om*/
    while ((c = in.read(buffer)) != -1) {
        out.write(buffer, 0, c);
    }
    session.fsync(out);
    in.close();
    out.close();

    session.commit(createIntentSender(context, sessionId));
    return true;
}

From source file:org.wso2.iot.agent.api.ApplicationManager.java

@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
private boolean installPackage(Uri fileUri) {

    InputStream in;// ww w.  ja  va 2s  . c  o m
    OutputStream out;
    String packageName = Preference.getString(context, Constants.PreferenceFlag.CURRENT_INSTALLING_APP);
    try {
        File application = new File(fileUri.getPath());
        in = new FileInputStream(application);
        PackageInstaller packageInstaller = context.getPackageManager().getPackageInstaller();
        PackageInstaller.SessionParams params = new PackageInstaller.SessionParams(
                PackageInstaller.SessionParams.MODE_FULL_INSTALL);
        params.setAppPackageName(packageName);
        // set params
        int sessionId = packageInstaller.createSession(params);
        PackageInstaller.Session session = packageInstaller.openSession(sessionId);
        out = session.openWrite(Constants.AGENT_PACKAGE, 0, -1);
        byte[] buffer = new byte[65536];
        int c;
        while ((c = in.read(buffer)) != -1) {
            out.write(buffer, 0, c);
        }
        session.fsync(out);
        in.close();
        out.close();

        session.commit(createIntentSender(context, sessionId, packageName));
        return true;
    } catch (IOException e) {
        Log.e(TAG, "Error occurred while installing application '" + packageName + "'", e);
    } catch (Exception e) {
        Log.e(TAG, "Error occurred while installing application '" + packageName + "'", e);
    }
    return false;
}