1. 程式人生 > >Android-->安裝程式(APK)後並啟動程式(APP)

Android-->安裝程式(APK)後並啟動程式(APP)

應用場景
一般現在的APP,都自帶自動更新功能,但是如果不處理的,安裝APK完成後,預設是不會啟動的;
這個時候,就有必要檢視此文了;

開始本文:
原理:就是通過,安裝程式之前,啟動一個定時任務,任務傳送一個廣播,廣播收到之後,啟動程式.

附上程式碼:
1:安裝APK的程式碼(需要root許可權)

    public static String install(String str) {
        String[] args = { "/system/bin/pm", "install", "-r", str };
        String result = "";
        ProcessBuilder processBuilder = new
ProcessBuilder(args); Process process = null; InputStream errIs = null; InputStream inIs = null; try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); int read = -1; process = processBuilder.start(); errIs = process.getErrorStream(); while
((read = errIs.read()) != -1) { // 獲取錯誤資訊 baos.write(read); } baos.write('\n'); inIs = process.getInputStream(); while ((read = inIs.read()) != -1) { // 獲取輸出資訊 baos.write(read); } byte[] data = baos.toByteArray(); //
result = new String(data); return result; // 返回值 } catch (Exception e) { return ""; } finally { try { if (errIs != null) { errIs.close(); } if (inIs != null) { inIs.close(); } } catch (Exception e) { } } }

2:按鈕事件程式碼

    public void install(View view) {
        String sdPath = Environment.getExternalStorageDirectory()
                .getAbsolutePath();

        //主要就是通過,安裝程式之前,啟動一個定時任務,任務傳送一個廣播,廣播收到之後,啟動程式
        Intent ite = new Intent(this, StartReceiver.class);
        ite.setAction("install_and_start");
        PendingIntent SENDER = PendingIntent.getBroadcast(this, 0, ite,
                PendingIntent.FLAG_CANCEL_CURRENT);
        AlarmManager ALARM = (AlarmManager) getSystemService(ALARM_SERVICE);
        ALARM.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 1000,
                SENDER);

        install(sdPath + "/InstallAndStartDemo.apk");
        finish();

    }

3:啟動程式的廣播

public class StartReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equalsIgnoreCase("install_and_start")) {
            Intent intent2 = new Intent(context, MainActivity.class);
            intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//注意,不能少
            context.startActivity(intent2);
        }
    }

}

4:清單檔案(Manifest.xml)

        <receiver android:name="com.example.installandstartdemo.StartReceiver">
            <intent-filter >
                <action android:name="install_and_start"/>
            </intent-filter>
        </receiver>

安裝APK的2種方式:

/**
* 使用root方式,靜態安裝apk
*/
private boolean installUseRoot(String filePath) {
  if (TextUtils.isEmpty(filePath))
      throw new IllegalArgumentException("Please check apk file path!");
  boolean result = false;
  Process process = null;
  OutputStream outputStream = null;
  BufferedReader errorStream = null;
  try {
      process = Runtime.getRuntime().exec("su");
      outputStream = process.getOutputStream();

      String command = "pm install -r " + filePath + "\n";
      outputStream.write(command.getBytes());
      outputStream.flush();
      outputStream.write("exit\n".getBytes());
      outputStream.flush();
      process.waitFor();
      errorStream = new BufferedReader(new InputStreamReader(process.getErrorStream()));
      StringBuilder msg = new StringBuilder();
      String line;
      while ((line = errorStream.readLine()) != null) {
          msg.append(line);
      }
      Log.d(TAG, "install msg is " + msg);
      if (!msg.toString().contains("Failure")) {
          result = true;
      }
  } catch (Exception e) {
      Log.e(TAG, e.getMessage(), e);
  } finally {
      try {
          if (outputStream != null) {
              outputStream.close();
          }
          if (errorStream != null) {
              errorStream.close();
          }
      } catch (IOException e) {
          outputStream = null;
          errorStream = null;
          process.destroy();
      }
  }
  return result;
}

/**
* 正常方式安裝APK
*/
private void installUseAS(String filePath) {
  Uri uri = Uri.fromFile(new File(filePath));
  Intent intent = new Intent(Intent.ACTION_VIEW);
  intent.setDataAndType(uri, "application/vnd.android.package-archive");
  mContext.startActivity(intent);
}

至此: 文章就結束了,如有疑問: QQ群:274306954 歡迎您的加入.