Android 静默安装的几种方式
@写在前面的话 Android 要想静默安装app,必须是系统应用或者具有Root权限,否则根本不可能实现静默安装 转载自@苍痕
1.系统API 。不是静默安装
- Intent intent = new Intent(Intent.ACTION_VIEW);
- intent.setDataAndType(Uri.parse("file://" + apkFilePath), "application/vnd.android.package-archive");
- intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- mContext.startActivity(intent);
- /**
- * install slient
- *
- * @param filePath
- * @return 0 means normal, 1 means file not exist, 2 means other exception error
- */
- public static int installSilent(String filePath) {
- File file = new File(filePath);
- if (filePath == null || filePath.length() == 0 || file == null || file.length() <= 0 || !file.exists() || !file.isFile()) {
- return 1;
- }
- String[] args = { "pm", "install", "-r", filePath };
- ProcessBuilder processBuilder = new ProcessBuilder(args);
- Process process = null;
- BufferedReader successResult = null;
- BufferedReader errorResult = null;
- StringBuilder successMsg = new StringBuilder();
- StringBuilder errorMsg = new StringBuilder();
- int result;
- try {
- process = processBuilder.start();
- successResult = new BufferedReader(new InputStreamReader(process.getInputStream()));
- errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream()));
- String s;
- while ((s = successResult.readLine()) != null) {
- successMsg.append(s);
- }
- while ((s = errorResult.readLine()) != null) {
- errorMsg.append(s);
- }
- } catch (IOException e) {
- e.printStackTrace();
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- try {
- if (successResult != null) {
- successResult.close();
- }
- if (errorResult != null) {
- errorResult.close();
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- if (process != null) {
- process.destroy();
- }
- }
- // TODO should add memory is not enough here
- if (successMsg.toString().contains("Success") || successMsg.toString().contains("success")) {
- result = 0;
- } else {
- result = 2;
- }
- Log.d("test-test", "successMsg:" + successMsg + ", ErrorMsg:" + errorMsg);
- return result;
- }
3. 静默安装:利用Runtime.getRuntime().exec()
- private static final String TAG = "test-test";
- private static final int TIME_OUT = 60 * 1000;
- private static String[] SH_PATH = {
- "/system/bin/sh",
- "/system/xbin/sh",
- "/system/sbin/sh"
- };
- public static boolean executeInstallCommand(String filePath) {
- String command = “pm install -r ” + filePath;
- Process process = null;
- DataOutputStream os = null;
- StringBuilder successMsg = new StringBuilder();
- StringBuilder errorMsg = new StringBuilder();
- BufferedReader successResult = null;
- BufferedReader errorResult = null;
- try {
- process = runWithEnv(getSuPath(), null);
- if (process == null) {
- return false;
- }
- successResult = new BufferedReader(new InputStreamReader(process.getInputStream()));
- errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream()));
- os = new DataOutputStream(process.getOutputStream());
- os.writeBytes(command + "\n");
- os.writeBytes("echo \"rc:\" $?\n");
- os.writeBytes("exit\n");
- os.flush();
- String s;
- while ((s = successResult.readLine()) != null) {
- successMsg.append(s);
- }
- while ((s = errorResult.readLine()) != null) {
- errorMsg.append(s);
- }
- // Handle a requested timeout, or just use waitFor() otherwise.
- if (TIME_OUT > 0) {
- long finish = System.currentTimeMillis() + TIME_OUT;
- while (true) {
- Thread.sleep(300);
- if (!isProcessAlive(process)) {
- break;
- }
- if (System.currentTimeMillis() > finish) {
- Log.w(TAG, "Process doesn't seem to stop on it's own, assuming it's hanging");
- // Note: 'finally' will call destroy(), but you might still see zombies.
- return true;
- }
- }
- } else {
- process.waitFor();
- }
- // In order to consider this a success, we require to things: a) a proper exit value, and ...
- if (process.exitValue() != 0) {
- return false;
- }
- return true;
- } catch (FileNotFoundException e) {
- Log.w(TAG, "Failed to run command, " + e.getMessage());
- return false;
- } catch (IOException e) {
- Log.w(TAG, "Failed to run command, " + e.getMessage());
- return false;
- } catch (InterruptedException e) {
- Log.w(TAG, "Failed to run command, " + e.getMessage());
- return false;
- } finally {
- if (os != null) {
- try {
- os.close();
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
- try {
- if (successResult != null) {
- successResult.close();
- }
- if (errorResult != null) {
- errorResult.close();
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- if (process != null) {
- try {
- // Yes, this really is the way to check if the process is still running.
- process.exitValue();
- } catch (IllegalThreadStateException e) {
- process.destroy();
- }
- }
- }
- }
- private static Process runWithEnv(String command, String[] customEnv) throws IOException {
- List<String> envList = new ArrayList<String>();
- Map<String, String> environment = System.getenv();
- if (environment != null) {
- for (Map.Entry<String, String> entry : environment.entrySet()) {
- envList.add(entry.getKey() + "=" + entry.getValue());
- }
- }
- if (customEnv != null) {
- for (String value : customEnv) {
- envList.add(value);
- }
- }
- String[] arrayEnv = null;
- if (envList.size() > 0) {
- arrayEnv = new String[envList.size()];
- for (int i = 0; i < envList.size(); i++) {
- arrayEnv[i] = envList.get(i);
- }
- }
- Process process = Runtime.getRuntime().exec(command, arrayEnv);
- return process;
- }
- /**
- * Check whether a process is still alive. We use this as a naive way to implement timeouts.
- */
- private static boolean isProcessAlive(Process p) {
- try {
- p.exitValue();
- return false;
- } catch (IllegalThreadStateException e) {
- return true;
- }
- }
- /** Get the SU file path if it exist */
- private static String getSuPath() {
- for (String p : SH_PATH) {
- File sh = new File(p);
- if (sh.exists()) {
- return p;
- }
- }
- return "su";
- }
4. 静默安装:利用反射调用API-PackageManager.installPackage()
- public static void installSilentWithReflection(Context context, String filePath) {
- try {
- PackageManager packageManager = context.getPackageManager();
- Method method = packageManager.getClass().getDeclaredMethod("installPackage",
- new Class[] {Uri.class, IPackageInstallObserver.class, int.class, String.class} );
- method.setAccessible(true);
- File apkFile = new File(filePath);
- Uri apkUri = Uri.fromFile(apkFile);
- method.invoke(packageManager, new Object[] {apkUri, new IPackageInstallObserver.Stub() {
- @Override
- public void packageInstalled(String pkgName, int resultCode) throws RemoteException {
- Log.d(TAG, "packageInstalled = " + pkgName + "; resultCode = " + resultCode) ;
- }
- }, Integer.valueOf(2), "com.ali.babasecurity.yunos"});
- //PackageManager.INSTALL_REPLACE_EXISTING = 2;
- } catch (NoSuchMethodException e) {
- e.printStackTrace();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
上面用到了反射调用,IPackageInstallObserver.class这个类在android sdk里面是没有的,您需要下载android_dependency.jar放到你工程的libs目录,这个jar提供了与PackageManager反射调用相关的类的定义。
- <!-- 静默安装 -->
- <uses-permission android:name="android.permission.INSTALL_PACKAGES" />
/** * 执行具体的静默安装逻辑,需要手机ROOT。 * @param apkPath * 要安装的apk文件的路径 * @return 安装成功返回true,安装失败返回false。 */ public boolean install(String apkPath) {boolean result = false; DataOutputStream dataOutputStream = null; BufferedReader errorStream = null; try {// 申请su权限 Process process = Runtime.getRuntime().exec("su"); dataOutputStream = new DataOutputStream(process.getOutputStream()); // 执行pm install命令 String command = "pm install -r " + apkPath + "\n"; dataOutputStream.write(command.getBytes(Charset.forName("utf-8"))); dataOutputStream.flush(); dataOutputStream.writeBytes("exit\n"); dataOutputStream.flush(); process.waitFor(); errorStream = new BufferedReader(new InputStreamReader(process.getErrorStream())); String msg = ""; String line; // 读取命令的执行结果 while ((line = errorStream.readLine()) != null) {msg += line; }Log.d("TAG", "install msg is " + msg); // 如果执行结果中包含Failure字样就认为是安装失败,否则就认为安装成功 if (!msg.contains("Failure")) {result = true; }} catch (Exception e) {Log.e("TAG", e.getMessage(), e); } finally {try {if (dataOutputStream != null) {dataOutputStream.close(); }if (errorStream != null) {errorStream.close(); }} catch (IOException e) {Log.e("TAG", e.getMessage(), e); }}return result; }
Android 静默安装的几种方式相关推荐
- android开启gps功能,android 打开GPS的几种方式
1.在讨论打开gps的之前先看下如何检测gps的开关情况: 方式一: boolean gpsEnabled = locationManager.isProviderEnabled(LocationMa ...
- android ui 最新教程,Android更新UI的五种方式,androidui五种
Android更新UI的五种方式,androidui五种handler.post activity.runOnUiThread view.post handler+Thread AsyncTask 例 ...
- 【Linux入门到精通系列讲解】Centos 7软件安装的三种方式
centos 软件安装的三种方式 Linux下面安装软件的常见方法: 一.yum 替你下载软件 替你安装 替你解决依赖关系 点外卖 缺少的东西 外卖解决 1.方便 简单 2.没有办法深入修改 yum ...
- Eclipse插件安装的三种方式
Eclipse插件安装总结通过个人的学习体会,将目前Eclipse插件安装的三种方式,总结如下: 第一种方法很简单,在Eclipse的主目录(%ECLIPSE_HOME%)下有一个plugins目录和 ...
- android实现后台静默安装,Android 静默安装实现方法
Android静默安装的方法,静默安装就是绕过安装程序时的提示窗口,直接在后台安装. 注意:静默安装的前提是设备有ROOT权限. 代码如下: /** * 静默安装 * @param file * @r ...
- android注册广播两种方式,Android 注册广播的两种方式对比
Android 注册广播的两种方式对比 1.常驻型广播 常驻型广播,当你的应用程序关闭了,如果有广播信息来,你写的广播接收器同样的能接受到, 他的注册方式就是在你的应用程序中的AndroidManif ...
- 【转】Linux下软件安装的几种方式
转自Linux下软件安装的几种方式 Linux 系统的/usr目录 Linux 软件安装到哪里合适,目录详解 Linux 的软件安装目录是也是有讲究的,理解这一点,在对系统管理是有益的 /usr:系统 ...
- mysql安装方法_MySQL安装的三种方式
MySQL安装的三种方式 Mysql安装方式对比 安装方式 安装简易度 使用简易度 定制化程度 适合范围 rpm包安装 简单 简单 低 仅适合redhat/centos系列linux 二进制安装 安装 ...
- android 图片方法,分享实现Android图片选择的两种方式
Android选择图片的两种方式: 第一种:单张选取 通过隐式启动activity,跳转到相册选择一张返回结果 关键代码如下: 发送请求: private static final int PICTU ...
- android使用其他应用打开方式,Android 启动activity的4种方式及打开其他应用的activity的坑...
Android启动的四种方式分别为standard,singleTop,singleTask,singleInstence. standard是最常见的activity启动方式,也是默认的启动的方式. ...
最新文章
- 使用Repeater的Template
- 真是祸从GPT-2口出,和AI聊会天,把别人隐私都给套出来了
- python包管理器修改镜像地址
- 程序员面对下列技术问题,如何做决策
- Android 抓包的一些命令 及 adb使用的一些注意事项
- 超级usb万能启动盘
- 使用webpack、babel、react、antdesign配置单页面应用开发环境
- android gdb 远程调试工具,gdb输入/输出错误远程调试到Android
- [转]Win XP常遇网络故障分析:局域网问题
- Ubuntu16.04+ ROS kinetic 使用kinect2 ORK功能包 linemod算法实现可乐罐识别
- 设施规划选址——重心法
- 安师大计算机专业排名多少,安师大的计算机专业怎么样
- 讯飞智能语音鼠标G50:AI语音、转写翻译、记录截图一键搞定!
- 麒麟系统开发笔记(一):国产麒麟系统搭建开发环境之虚拟机安装
- 《数据访问 - 第01章 文件 - 文件和流的概念》
- STC51单片机20——DS1302可调电子时钟1602显示proteus仿真
- 弹性力学第五版pdf_弹性力学5-圣维南原理.pdf
- sat求解器解哈密顿回路
- 重磅 l 全国首例微信三级分销被认定为传销,三级分销“身世”揭秘(下)
- 《Android源码设计模式解析与实战》读书笔记(十三)