2016-09-06 28 views
0

我正在使用此类以编程方式更新我的应用程序,它完美地工作。Android包管理器 - 安装并打开APK

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来实现吗?

+0

我假设你在根设备上,对不对?因为我得到“权限被拒绝”异常 – Maragues

回答

1
String cmd = "am start -n " + getApplicationContext().getPackageName() + "/." + getActivity().getClass().getSimpleName(); 
... 
os.writeBytes("pm install -r " + filename + " && " + cmd); 
...