Example usage for android.content.pm PackageInstaller createSession

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

Introduction

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

Prototype

public int createSession(@NonNull SessionParams params) throws IOException 

Source Link

Document

Create a new session using the given parameters, returning a unique ID that represents the session.

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 ww .j a v a2s  . com*/
    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;/*from w  w w.  j  a v  a2 s .  co  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;
}