Android软件包管理器 - 安装并打开APK

时间:2016-09-06 07:27:32

标签: android

我正在使用这个类以编程方式更新我的应用程序,这非常有效。

public static class UpdateApp extends AsyncTask < String, Void, Void > {
 private Context context;
 public void setContext(Context contextf) {
  context = contextf;
 }

 @Override
 protected Void doInBackground(String...arg0) {
  try {
   URL url = new URL(arg0[0]);
   HttpURLConnection c = (HttpURLConnection) url.openConnection();
   c.setRequestMethod("GET");
   c.setDoOutput(true);
   c.connect();

   String PATH = "/mnt/sdcard/Download/";
   File file = new File(PATH);
   file.mkdirs();
   File outputFile = new File(file, "update.apk");
   if (outputFile.exists()) {
    outputFile.delete();
   }
   FileOutputStream fos = new FileOutputStream(outputFile);

   InputStream is = c.getInputStream();

   byte[] buffer = new byte[1024];
   int len1 = 0;
   while ((len1 = is.read(buffer)) != -1) {
    fos.write(buffer, 0, len1);
   }
   fos.close();
   is.close();

   String filename = "/mnt/sdcard/Download/update.apk";
   File filez = new File(filename);
   if (filez.exists()) {
    try {
     final String command = "pm install -r " + filez.getAbsolutePath();
     Process proc = Runtime.getRuntime().exec(new String[] {
      "su",
      "-c",
      command
     });
     proc.waitFor();
    } catch (Exception e) {
     e.printStackTrace();
    }
   }



  } catch (Exception e) {
   //Log.e("UpdateAPP", "Update error! " + e.getMessage());
  }
  return null;
 }
}

如您所见,该类使用"pm install"命令。

我想要做的是在安装完成后立即运行更新的应用程序,这样用户就不会停留在应用程序之外。有什么方法可以通过包管理器或adb来实现这个目标吗?

1 个答案:

答案 0 :(得分:1)

{{1}}