Search code examples
javaandroiddownloadandroid-4.0-ice-cream-sandwichandroid-4.2-jelly-bean

Downloading problems with android 4.0/ 4.1.2


I am having a problem with android 4.0 or higher when, I'm Trying to download a file from a URL, It works fine in android Galaxy Y 2.3 / 2.2 but when I use the same code for Galaxy S3(4.1.2) the download starts but it doesn't finish.

Code:

 public void update() {
    Log.d(TAG, "Método para fazer a atualização iniciado.");
    try {
        Log.d(TAG, "Conectando com a internet...");
        URL url = new URL(
                url);
        HttpURLConnection c = (HttpURLConnection) url.openConnection();
        c.setRequestMethod("GET");
        c.setDoOutput(true);
        c.connect();

        Log.d(TAG, "Iniciando arquivo...");
        String PATH = Environment.getExternalStorageDirectory()
                + "/test/Update/";
        File file = new File(PATH);
        file.mkdirs();
        File outputFile = new File(file, "test.apk");
        FileOutputStream fos = new FileOutputStream(outputFile);

        Log.d(TAG, "Iniciando Stream...");
        InputStream is = c.getInputStream();

        Log.d(TAG, "Iniciando o download...");
        byte[] buffer = new byte[1024];
        int len1 = 0;
        while ((len1 = is.read(buffer)) != -1) {
            fos.write(buffer, 0, len1);
        }
        fos.close();
        is.close();

        Log.d(TAG, "Iniciando instalador...");
        final Intent promptInstall = new Intent(Intent.ACTION_VIEW);
        promptInstall.setDataAndType(Uri.fromFile(new File(PATH + "test.apk")),"application/vnd.android.package-archive");
        promptInstall.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(promptInstall);
        Log.d(TAG, "Instalador iniciado com sucesso!");
    } catch (MalformedURLException e) {
        Log.e(TAG, "Malformed URL. Mensagem: " + e.getMessage()
                + " Causa: " + e.getCause());
    } catch (IOException e) {
        Log.e(TAG, "IOException. Mensagem: " + e.getMessage() + " Causa: "
                + e.getCause());
    } catch (Exception e) {
        Log.e(TAG, "Exception. Mensagem: " + e.getMessage() + " Causa: "
                + e.getCause());
    }
}

Obs:There is no Error, It just start the download and stop it. File size : 126,188 bytes and in the Galaxy S3 6,403 bytes


Solution

  • Use AsyncTask to make your request.

    AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.