2012-09-22 84 views
0

我需要通过程序下载.apk文件,然后启动其活动。 我使用的代码如下Android下载的.apk文件损坏

private String downloadFile(String sourceURL, String destinationPath) 
    { 
     try { 
      URL url = new URL(sourceURL); 
      URLConnection connection = url.openConnection(); 
      connection.connect(); 

      // download the file 
      InputStream input = new BufferedInputStream(url.openStream()); 
      OutputStream output = new FileOutputStream(destinationPath); 

      byte data[] = new byte[1024]; 
      int count; 
      while ((count = input.read(data)) > 0) { 
       output.write(data, 0, count); 
      } 

      output.flush(); 
      output.close(); 
      input.close(); 

//此编辑:使文件RW,否则apk文件将不被安装 调用Runtime.getRuntime()EXEC( “搭配chmod 666” +的DestinationPath) ;

  message = "OK"; 
     } 
     catch (MalformedURLException e) { 
      message = "Malformed URL error: " + e.getMessage(); 
     } 
     catch (ProtocolException e) { 
      message = "Protocol exception error: " + e.getMessage(); 
     } 
     catch (FileNotFoundException e) { 
      message = "File not found error: " + e.getMessage(); 
     } 
     catch (IOException e) { 
      e.printStackTrace(); 
      message = "Failed to download the file : " + e.getMessage(); 
     } 
     return message; 
    } 

我提到我先为文本文件调用方法,然后再调用apk文件。因此,每次我在本地处理文件时,我都知道发生了什么问题。通过这种方式,我知道文本文件已正确下载。但.apk文件已损坏。因为我在本地开发,可以访问DDMS和本地主机(IP:10.0.2.2),所以我可以坚信罪魁祸首就是上面的代码。当我通过DDMS与原始.apk文件人为地替换“下载”文件时,所有后续处理都是OK。另外,当我比较原始文件和下载的.apk文件时,我遇到了不同之处。 我在做什么错? 谢谢 PS:搜索,我意识到,虽然是一个流行的问题,但没有一致的答案。就我而言,我将其确定为纯粹的下载方法问题。

+0

服务器是否将APK作为二进制文件发送? Content-Type标头的值是什么? – Rajesh

+0

有趣。你建议setRequestProperty为二进制?如果是这样,什么是正确的参数(因为它似乎是相当面向应用程序的格式)。就像connection.setRequestProperty(“content-type”,“multipart/form-data”)? –

+0

sourceURL的类型是什么?它是一个HTTP请求?你从哪里下载文件?您将不得不在服务器代码中设置Content-Type标头。 – Rajesh

回答

0

请参阅上面的编辑线下的答案。已实施,工作正常,可以帮助其他人