標籤: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 @Override10 public void run() {11 // TODO Auto-generated method stub12 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 block39 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(downloadPath10 + "/" + 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 @Override25 public void run() {26 // TODO Auto-generated method stub27 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 }