Android程序中安装APP

来源:互联网 发布:最新avtaobao域名 编辑:程序博客网 时间:2024/06/05 08:08

                                     Android程序中安装APP

方法一

这种方法通过 Intent 机制,调出系统安装应用,重新安装应用的话,会保留原应用的数据。

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

方法二

这种方法

  1. 需要对apk进行系统签名
  2. 需要系统权限,在manifest头部加上 android:sharedUserId=“android.uid.system”
  3. 需要安装权限 <uses-permission android:name=“android.permission.INSTALL_PACKAGES” />
  4. 稍微修改下命令就可以用于静默卸载
  5. 可以把apk push到/system/app目录,也可以直接安装,两种方式都有效

如果这个apk是系统应用( /system/app/ ),那么对它使用这种方式进行更新版本时,会在 /data/app/ 下面安装apk包,更新后的应用可以直接卸载,一旦卸载,在桌面上显示的就是原来的系统应用( /system/app/ )。对这个系统应用进行多次更新,更新后均会在/data/app目录下,而之前的包会被替换掉,在这个目录只会有一个该应用的包。


private String excuteCommand() {String result = "";ProcessBuilder processBuilder = new ProcessBuilder(args);Process process = null;InputStream errIs = null;InputStream inIs = null;try {ByteArrayOutputStream baos = new ByteArrayOutputStream();int read = -1;process = processBuilder.start();errIs = process.getErrorStream();while ((read = errIs.read()) != -1) {baos.write(read);}baos.write('\n');inIs = process.getInputStream();while ((read = inIs.read()) != -1) {baos.write(read);}byte[] data = baos.toByteArray();result = new String(data);} catch (IOException e) {e.printStackTrace();} catch (Exception e) {e.printStackTrace();} finally {try {if (errIs != null) {errIs.close();}if (inIs != null) {inIs.close();}} catch (IOException e) {e.printStackTrace();}if (process != null) {process.destroy();}}return result;}
//代码执行后,如果安装成功的话获取到的result值是“pkg: /data/local/tmp/test.apk /nSuccess”,如果是失败的话,则没有结尾的“Success”。
 public static boolean installSilence(String apkPath) {        String[] args = { "pm", "install", "-r", apkPath };        String result = excuteCommand(args);        if (StringUtil.isEmpty(result)) {            return false;        } else {            return result.lastIndexOf("Success") > 0;        }    }

卸载app


方法一

通过 Intent 机制,调出系统卸载应用。

Uri packageURI = Uri.parse("package:com.demo.test");   // 包名Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);   startActivity(uninstallIntent);

方法二
直接调用卸载接口。
PackageInstallObserver observer = new PackageInstallObserver(); pm.installPackage( mPackageURI , observer, installFlags);//使用这种方法卸载应用需要权限: android.permission.DELETE_PACKAGES



0 0
原创粉丝点击