【问题标题】:How to download and automatic install apk from url in android如何从android中的url下载和自动安装apk
【发布时间】:2014-08-18 09:00:51
【问题描述】:

我正在尝试以编程方式从给定的 URL 下载 .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);
        }

【问题讨论】:

  • Google 不会喜欢你正在尝试做的事情。
  • 请提供logcat错误
  • Swapna, FileNotFound 意味着该文件被放错了我认为的其他位置,无论您查看的文件不在那个位置。

标签: android android-asynctask apk inputstream


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    试试下面的代码

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

    您正在做的是删除文件,当它已经存在时,FileOutputStream 将无法获取您要下载apk 的文件。

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

    如果您有疑问,请询问!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-28
      • 2022-01-16
      • 2015-05-16
      • 2022-07-01
      • 2018-08-19
      • 2011-08-22
      • 1970-01-01
      相关资源
      最近更新 更多