简体   繁体   English

如何在Android中从URL下载并自动安装APK

[英]How to download and automatic install apk from url in android

I'm trying to programmatically download an .apk file from a given URL and then install it, but I am getting a FileNotFoundException . 我正在尝试以编程方式从给定的URL下载.apk文件,然后安装它,但是却收到FileNotFoundException What could be a possible reason for the issue? 这个问题可能是什么原因?

        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);
        }

You just replaced by InputStream is = c.getInputStream(); 您刚刚被InputStream替换的是= c.getInputStream(); to given code. 给定的代码。

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

Try the following code 试试下面的代码

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

   outputFile.createNewFile();
 }

What you are doing is deleting the file, when it already exist, then FileOutputStream will not get file where you want to download the apk . 您正在做的是删除文件,如果文件已经存在,则FileOutputStream将不会在您要下载apk位置获取文件。

If the file already exist, FileOutputStream will override the content with new update. 如果文件已经存在,则FileOutputStream将使用新的更新覆盖内容。

If you have queries, do ask!! 如果您有疑问,请询问!!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM