从其他应用程序安装来自外部存储的apk而无需确认活动

时间:2015-03-12 14:48:36

标签: java android android-intent android-activity apk

这是使用确认活动从外部存储安装apk文件的代码示例:

        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/app-debug.apk")), "application/vnd.android.package-archive");
        startActivity(intent);

我需要从外部存储安装apk而无需确认活动。 有可能吗?

2 个答案:

答案 0 :(得分:0)

在root设备上,您可以使用此代码,该代码也会在非root设备上恢复询问确认。这会自动更新实际运行的应用程序并重新启动它。

// path is the complete path to the APK file, startActivityName is the name of the activity to start once the install is complete.
private boolean rootUpdateAPK(String path, String startActivityName)
{       
    final String libs = "LD_LIBRARY_PATH=/vendor/lib:/system/lib ";
    final String[] commands = {
            libs + "pm install -r " + path,
            //              libs + "reboot"
            //      };
            libs + "am start -n " +  this.getPackageName() + "/."+startActivityName
    };
    execute_as_root(commands);  // not supposed to return if successful

    // device is not rooted, let's do it the "regular" way.

    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setDataAndType(Uri.fromFile(new File(path)), "application/vnd.android.package-archive");
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);

    return false;
}

private void execute_as_root( String[] commands ) {
    try {
        Process p = Runtime.getRuntime().exec( "su" );
        InputStream es = p.getErrorStream();
        DataOutputStream os = new DataOutputStream(p.getOutputStream());

        for( String command : commands ) {
            TVLog.i(TAG,"Execute as root: "+command);
            os.writeBytes(command + "\n");
        }
        os.writeBytes("exit\n");
        os.flush();
        os.close();

        int read;
        byte[] buffer = new byte[4096];
        String output = new String();
        while ((read = es.read(buffer)) > 0) {
            output += new String(buffer, 0, read);
        }

        p.waitFor();
        TVLog.i(TAG, output.trim() + " (" + p.exitValue() + ")");
    } catch (IOException e) {
        TVLog.i(TAG, e.getMessage());
    } catch (InterruptedException e) {
        TVLog.i(TAG, e.getMessage());
    }
}

答案 1 :(得分:0)

我解决了问题。 为了从任何存储安装apk,我们可以使用PackageManager和隐藏的api。 这是代码示例:

    PackageManager manager = getPackageManager();
    Uri packageURI = Uri.fromFile(new File(pathToApkFile));
    manager.installPackage(packageURI, null, 2, "app");

installPackage它是隐藏的api,你需要在aosp中构建你的应用程序