分享一個android靜默安裝,安裝後重新啟動app的方法,androidapp

來源:互聯網
上載者:User

分享一個android靜默安裝,安裝後重新啟動app的方法,androidapp

 一:需求簡介

  之前boss提出一個需求,運行在廣告機上的app,需要完成自動升級的功能,廣告機是非觸控螢幕的,不能通過手動點擊,所以app必須做到自動下載,自動安裝升級,並且安裝完成後,app還要繼續運行,最好不藉助其它app來實現以上功能。

 二:實現思路

  實現這個功能第一個想到的方法就是靜默安裝,由於廣告機已經root,靜默安裝比較順利,安裝app的主要代碼如下:

/*
  @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 ,完整代碼如下:

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自動需行的需求。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.