一:需求简介linux
以前boss提出一个需求,运行在广告机上的app,须要完成自动升级的功能,广告机是非触摸屏的,不能经过手动点击,因此app必须作到自动下载,自动安装升级,而且安装完成后,app还要继续运行,最好不借助其它app来实现以上功能。android
二:实现思路app
实现这个功能第一个想到的方法就是静默安装,因为广告机已经root,静默安装比较顺利,安装app的主要代码以下:spa
/*
@pararm apkPath 等待安装的app全路径,如:/sdcard/app/app.apk
**/
private static boolean clientInstall(String apkPath) { PrintWriter PrintWriter = null; Process process = null; try { process = Runtime.getRuntime().exec("su"); PrintWriter = new PrintWriter(process.getOutputStream()); PrintWriter.println("chmod 777 " + apkPath); PrintWriter .println("export LD_LIBRARY_PATH=/vendor/lib:/system/lib"); PrintWriter.println("pm install -r " + apkPath); // PrintWriter.println("exit"); PrintWriter.flush(); PrintWriter.close(); int value = process.waitFor(); Logger.e("静默安装返回值:"+value); return returnResult(value); } catch (Exception e) { e.printStackTrace(); Logger.e("安装apk出现异常"); } finally { if (process != null) { process.destroy(); } } return false; }
以上方法能顺利安装,但不能实现软件安装完成后,软件还能继续运行,由于安装后,当前app的进程已经被kill了。没法实现boss提出的,安装后软件正常运行的需求,此时若是咱们还想着用android来实现这个需求,是没法实现的,由于app进程被kill了,因此须要借助第三方来启动咱们的app,我第一时间想到的就是linux执行am start命令,但这个命令不能当即执行,因此须要sleep来实现这个需求,命令格式以下 sleep 时间(单位秒),am start -n ,完整代码以下:code
private void execLinuxCommand(){ String cmd= "sleep 120; am start -n 包名/包名.第一个Activity的名称"; //Runtime对象 Runtime runtime = Runtime.getRuntime(); try { Process localProcess = runtime.exec("su"); OutputStream localOutputStream = localProcess.getOutputStream(); DataOutputStream localDataOutputStream = new DataOutputStream(localOutputStream); localDataOutputStream.writeBytes(cmd); localDataOutputStream.flush(); Logger.e("设备准备重启"); } catch (IOException e) { Logger.i(TAG+"strLine:"+e.getMessage()); e.printStackTrace(); } }
涉及到的权限:对象
<uses-permission android:name="android.permission.INSTALL_PACKAGES" />
注意:不是全部root过的设备,都能执行Process localProcess = runtime.exec("su");这个须要硬件支持,这个坑我遇到过。经过以上两个方法就能实现静默安装,安装完成后,app自动需行的需求。blog