android 代码卸载和安装应用

1.安装应用

//下载应用到自己的手机上,本例将安装包放在asset上,直接读取写入手机的存储卡路径中

清单文件声明权限

//android8.0需要install_packages权限,清单文件注册即可,无需动态申请权限

 
    
    

android 7.0以上使用FileProvider

清单文件中声明

 
            
        

provide_paths.xml文件 (写出所需的目录即可)



    
    
    
    
    
    
    
    
    
    


1) . 适配android6.0以上

//android8.0以后,权限申请的话,一个权限组的,只要同意一个权限就会默认整个权限组同意,即android8.0以下两个权限只有同意一个即可。

 //该执行需要两个权限
                String[] permissions = new String[]{
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE
                };
                //判断当前权限 低版本直接通过,高版本判断权限
                if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
                    if (ActivityCompat.checkSelfPermission(this, permissions[0]) == PackageManager.PERMISSION_GRANTED &&
                            ActivityCompat.checkSelfPermission(this, permissions[1]) == PackageManager.PERMISSION_GRANTED) {
                        installApk();
                    } else {
                        ActivityCompat.requestPermissions(this, permissions, 11);
                    }
                } else {
                    installApk();
                }

处理权限申请

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 11:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                    installApk();
                }
                break;
        }
    }

2)、准备安装的apk文件

private void installApk(){ 
File cacheDir = getExternalCacheDir();
        String CACHE_PATH;
        if (cacheDir != null) {
            CACHE_PATH = cacheDir.getAbsolutePath();
        } else {
            CACHE_PATH = Environment.getExternalStorageDirectory().getAbsolutePath();
        }
        String path = CACHE_PATH + System.getProperty("file.separator") + "test.apk";
        final File apkFile = new File(path);//创建存储路径
        if (!apkFile.exists()) {
            Executor executor = Executors.newSingleThreadExecutor();
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    try {//将asset目录下的文件读取出来
                        InputStream inputStream = getAssets().open("test.apk");
                        OutputStream os = null;
                        os = new BufferedOutputStream(new FileOutputStream(apkFile, false));
                        byte data[] = new byte[8192];
                        int len;
                        while ((len = inputStream.read(data, 0, 8192)) != -1) {
                            os.write(data, 0, len);
                        }
                        if (inputStream != null)
                            inputStream.close();
                        if (os != null)
                            os.close();

                    } catch (IOException e) {
                        e.printStackTrace();
                    }//读取文件之后执行安装
                    install(apkFile);
                }
            });
        } else {//有文件的时候直接执行安装
            install(apkFile);
        }
}

3)、开始安装文件 android8.0添加一个允许安装第三方应用,需要用户手动授权处理

可以用canRequestPackageInstalls来判断用户是否授权,未授权,跳转到相应的页面进行操作。

   /**
     * 跳转到安装页面
     *
     * @param apkFile
     */
    private void install(File apkFile) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            boolean b = getPackageManager().canRequestPackageInstalls();
            if (b) {
                startInstall(apkFile);
            } else {//跳转到应用授权安装第三方应用权限
                Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
                startActivity(intent);
            }
        } else {
            startInstall(apkFile);
        }
    }

4)、跳转到应用的安装页面,将文件带到安装页面进行安装

android8.0需要添加授权fileprovider授权权限,不能使用newtask标志位

  private void startInstall(File apkFile) {
        Intent intent1 = new Intent(Intent.ACTION_VIEW);
        Uri data;
        String type = "application/vnd.android.package-archive";
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            data = Uri.fromFile(apkFile);
            intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        } else {
            intent1.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            String authority = getPackageName() + ".provider";
            data = FileProvider.getUriForFile(this, authority, apkFile);
            intent1.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        intent1.setDataAndType(data, type);
        startActivity(intent1);
    }

2.静默安装应用

获取文件跟上面的一样

判断当前设备是否有root权限

   private boolean isRoot(){
        String su = "su";
        //手机本来已经有root权限(/system/bin/su已经存在,adb shell里面执行su就可以切换root权限下)
        String[] locations = {"/system/bin/", "/system/xbin/", "/sbin/", "/system/sd/xbin/",
                "/system/bin/failsafe/", "/data/local/xbin/", "/data/local/bin/", "/data/local/"};
        for (String location : locations) {
            if (new File(location + su).exists()) {
                return true;
            }
        }
        return false;
    }
  private boolean installSilent(File apkFile) {
        boolean isDeviceRoot = isRoot();
        String filePath = '"' + apkFile.getAbsolutePath() + '"';
        String command = "LD_LIBRARY_PATH=/vendor/lib*:/system/lib* pm install " + filePath;
        CommandResult commandResult = execCmd(new String[]{command}, isDeviceRoot, true);
        if (commandResult.successMsg != null && commandResult.successMsg.toLowerCase().contains("success")) {
            return true;//安装成功
        } else {
            return false;//安装失败
        }
    }

命令行执行

  private static final String LINE_SEP = System.getProperty("line.separator");

    private CommandResult execCmd(String[] commands, boolean isRoot, boolean isNeedResultMsg) {
        int result = -1;
        if (commands == null || commands.length == 0) {
            return new CommandResult(result, null, null);
        }
        Process process = null;
        BufferedReader successResult = null;
        BufferedReader errorResult = null;
        StringBuffer successMsg = null;
        StringBuffer errorMsg = null;

        DataOutputStream os = null;
        try {
            //root过的手机上面获得root权限
            process = Runtime.getRuntime().exec(isRoot ? "su" : "sh");
            os = new DataOutputStream(process.getOutputStream());
            for (String command : commands) {
                if (command == null)
                    continue;
                os.write(command.getBytes());
                os.writeBytes(LINE_SEP);
                os.flush();
            }
            os.writeBytes("exit" + LINE_SEP);
            os.flush();
            result = process.waitFor();
            if (isNeedResultMsg) {
                successMsg = new StringBuffer();
                errorMsg = new StringBuffer();
                successResult = new BufferedReader(new InputStreamReader(process.getInputStream(),
                        "UTF-8"));
                errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream(),
                        "UTF-8"));
                String line;
                if ((line = successResult.readLine()) != null) {
                    successMsg.append(line);
                    while ((line = successResult.readLine()) != null) {
                        successMsg.append(LINE_SEP).append(line);
                    }
                }
                if ((line = errorResult.readLine()) != null) {
                    errorMsg.append(line);
                    while ((line = errorResult.readLine()) != null) {
                        errorMsg.append(LINE_SEP).append(line);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            try {
                if (os != null)
                    os.close();
                if (successResult != null)
                    successResult.close();
                if (errorResult != null)
                    errorResult.close();
                if (process != null)
                    process.destroy();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return new CommandResult(result, successMsg == null ? null : successMsg.toString(),
                errorMsg == null ? null : errorMsg.toString());
    }

模型

public class CommandResult {

    public int result;
    public String successMsg;
    public String errorMsg;

    public CommandResult(int result, String successMsg, String errorMsg) {
        this.result = result;
        this.successMsg = successMsg;
        this.errorMsg = errorMsg;
    }
}

3.卸载应用

Intent intent=new Intent(Intent.ACTION_DELETE);
intent.setData(Uri.parse("package:包名"));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

4.静默卸载应用

  /**
     * 卸载应用成功&失败
     * @param packageName
     * @param isKeepData
     * @return
     */
    private boolean uninstallSilent(String packageName,boolean isKeepData){
        boolean isRoot=isRoot();
        String command="LD_LIBRARY_PATH=/vendor/lib*:/system/lib* pm uninstall "+(isKeepData?"-k":"")+packageName;
        CommandResult commandResult=execCmd(new String[]{command},isRoot,true);
        if (commandResult.successMsg!=null
                && commandResult.successMsg.toLowerCase().contains("success")){
            return true;
        }else {
            return false;
        }
    }

你可能感兴趣的:(android)