如何在android中从url下载并自动安装apk

时间:2014-08-18 09:00:51

标签: android android-asynctask apk inputstream

我正在尝试以编程方式从给定的网址下载.apk文件然后安装它,但我得到的是FileNotFoundException。这个问题可能是什么原因?

        try {
                URL url = new URL(fileURL);
                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, "VersionUpdate.apk");
                if(outputFile.exists()){
                    outputFile.delete();
                }
                FileOutputStream fos = new FileOutputStream(outputFile);

**//Getting error in this line** 

                InputStream is = c.getInputStream();



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




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

    @Override
        protected void onPostExecute(String unused) {
            //dismiss the dialog after the file was downloaded
            dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
            Intent intent = new Intent(Intent.ACTION_VIEW); 
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(Uri.parse("file:///sdcard/download/VersionUpdate.apk"),"application/vnd.android.package-archive"); 
            startActivity(intent);
        }

2 个答案:

答案 0 :(得分:2)

您刚刚将 InputStream is = c.getInputStream(); 替换为给定代码。

InputStream is ;
    int status = c.getResponseCode();
    if (status != HttpURLConnection.HTTP_OK)
       is = c.getErrorStream();
    else
       is = c.getInputStream();

答案 1 :(得分:0)

尝试以下代码

 File outputFile = new File(file, "VersionUpdate.apk");
 if(!outputFile.exists())
 {

   outputFile.createNewFile();
 }

您正在执行的操作是删除文件,如果文件已存在,则FileOutputStream将无法获取您要下载apk的文件。

如果该文件已存在,FileOutputStream将使用新更新覆盖内容。

如果您有疑问,请询问!!