1.实现静默安装和卸载需要两个权限
<uses-permission android:name="android.permission.INSTALL_PACKAGES" />
<uses-permission android:name="android.permission.DELETE_PACKAGES" />2.你的app需要放置在System\app或者System\priv-app目录下,也就是说要有root权限或者是系统应用才行
3.我都是选择adb命令行的方式,我看见有的博客是用反射来做的,不过我是试过了,在API25的情况下我没跑通,可能是我自己的问题。废话不多说上代码:
(1)静默安装:
- private boolean install()
- {
- String[] args = {"pm", "install", "-r", packageUri.getPath()};
- String result = null;
- 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(Exception e){
- e.printStackTrace();
- }finally{
- try{
- if(errIs != null){
- errIs.close();
- }
- if(inIs != null){
- inIs.close();
- }
- }catch(Exception e){
- e.printStackTrace();
- }
- if(process != null){
- process.destroy();
- }
- }
- if(result != null && (result.endsWith("Success")||result.endsWith("Success\n")))
- {
- return true;
- }
- return false;
- }
(2)静默卸载:
- private void uninstall2() {
- String[] args = { "pm", "uninstall", "com.popcap.pvzthird" };
- String result = null;
- 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 (Exception e) {
- e.printStackTrace();
- } finally {
- try {
- if (errIs != null) {
- errIs.close();
- }
- if (inIs != null) {
- inIs.close();
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- if (process != null) {
- process.destroy();
- }
- }
- }