Android程序中安装APP

                                     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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值