标签:android style class blog code http
这几天在做一个新的功能,需要用到静默安装,所以在网上找了一些静默安装的资料就在这里记录一下吧。其实实现静默安装的原理就是请求Android手机的root权限,通过执行Linux命令来安装APK到手机系统,其实代码不是很多,就在这里列一下吧,以后用的时候可以直接翻出来:
1 public class MyThread extends Thread { 2 private String path; 3 4 public MyThread(String path) { 5 // TODO Auto-generated constructor stub 6 this.path = path; 7 } 8 9 @Override 10 public void run() { 11 // TODO Auto-generated method stub 12 super.run(); 13 14 Process process = null; 15 OutputStream out = null; 16 InputStream in = null; 17 18 try { 19 process = Runtime.getRuntime().exec("su"); 20 out = process.getOutputStream(); 21 22 out.write(("pm install -r " + path + "\n").getBytes()); 23 in = process.getInputStream(); 24 int len = 0; 25 byte[] bs = new byte[256]; 26 27 while (-1 != (len = in.read(bs))) { 28 String state = new String(bs, 0, len); 29 if (state.equals("Success\n")) { 30 31 Message m = new Message(); 32 m.arg1 = 1; 33 DownLoadService.this.myHandler.sendMessage(m); 34 35 } 36 } 37 } catch (IOException e) { 38 // TODO Auto-generated catch block 39 e.printStackTrace(); 40 41 } 42 } 43 }
其主要步骤为:
1.执行Android手机的su命令,如果手机已经root过了,一般情况下Android手机会有一个提示框,提示你是否给予root权限,
2.如果Android获得了root权限并且同意该应用的权限,则调用pm命令进行安装
3.安装完成后可以通过读取命令的输出流来判断应用是否安装成功,一般会获得一个“success”的字符换
出现的问题:
1.如果用户拒绝授予root权限,在这里没有办法正确判断
2.如果在用户拒绝授予root权限的情况下,读取起错误流可以获得失败的判断。但是在读取了起错误流的情况下,如果用户授予其root权限,则不能正常执行安装操作
目前这两个问题还不知道怎么判断,希望有做过的朋友指点一下
Http下载APK文件,具体代码如下:
1 HttpGet httpGet = new HttpGet(url); 2 try { 3 HttpResponse httpResponse = new DefaultHttpClient() 4 .execute(httpGet); 5 6 if (httpResponse.getStatusLine().getStatusCode() == 200) { 7 InputStream is = httpResponse.getEntity().getContent(); 8 // 开始下载apk文件 9 FileOutputStream fos = new FileOutputStream(downloadPath 10 + "/" + name+".apk"); 11 byte[] buffer = new byte[8192]; 12 int count = 0; 13 while ((count = is.read(buffer)) != -1) { 14 fos.write(buffer, 0, count); 15 } 16 fos.close(); 17 is.close(); 18 Log.d(TAG, "apk path = " + downloadPath + "/" + name+".apk"); 19 20 final String path = downloadPath + "/" + name+".apk"; 21 22 timer = new Timer(); 23 timer.schedule(new TimerTask() { 24 @Override 25 public void run() { 26 // TODO Auto-generated method stub 27 28 Message m = new Message(); 29 m.arg1 = 2; 30 Bundle bundle = new Bundle(); 31 bundle.putString("path", path); 32 m.setData(bundle); 33 DownLoadService.this.myHandler.sendMessage(m); 34 } 35 }, timeOut); 36 37 new MyThread(path).start(); 38 } 39 } catch (Exception e) { 40 }
Android 请求root权限实现静默安装,布布扣,bubuko.com
标签:android style class blog code http
原文地址:http://www.cnblogs.com/jjxxjnzy/p/3789985.html