androiddownloadcorrupt-data

Downloaded .apk file in Android corrupted


I need to download by program an .apk file then launching its activity. The code I am using is the following

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

// EDITED here: Make the file rw, otherwise the apk file will not be installed 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;
    }

I mention that I call the method first for a text file, then for an apk file. Each time I process the files locally, therefore, somehow I know what's going wrong or not. In this way I know that the text file is downloaded correctly. But the .apk file is corrupted. Because I develop locally, with access to DDMS and localhost (the IP: 10.0.2.2) I can firmly state that the culprit is the code above. When I artificially replace the 'downloaded' file, through DDMS, with the original .apk file, all processing that follows is Ok. In addition, I have byes difference when I compare the original and the downloaded .apk files. What am I doing wrong? Thanks PS: Searching, I realized that, while is a popular issue, there is no consistent answer to it. In my case I identified it as purely a download method issue.


Solution

  • Please see above the answer under the EDITED line. Implemented, works fine, that may help others