java - android 4.0/4.1.2 下载问题

标签 java android download android-4.0-ice-cream-sandwich android-4.2-jelly-bean

当我尝试从 URL 下载文件时,我在使用 Android 4.0 或更高版本时遇到问题,它在 Android Galaxy Y 2.3/2.2 中工作正常,但当我对 Galaxy S3(4.1.1) 使用相同的代码时,它会正常工作。 2) 下载开始但未完成。

代码:

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

观察:没有错误,只是开始下载然后停止。 文件大小:126,188 字节,Galaxy S3 为 6,403 字节

最佳答案

使用AsyncTask提出您的请求。

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.

关于java - android 4.0/4.1.2 下载问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14319335/

相关文章:

java - Quickblox 登录无法使用 3.3.1 sdk

java - 使用 Java 数组列表

Java 中断构建器模式

android - 可绘制 ldpi/mdpi/hdpi/xhdpi 文件夹的最佳位图大小是多少?

javascript - Chrome 下载多个文件

javascript - 下载二进制文件而不触发 onbeforeunload

java - DWR 对 JavaScript 变量的响应

android - 如何设置 Android 微调器弹出窗口的样式?

android - 没有viewpager的自定义Tablayout隐藏了textview

curl - 使用curl下载时如何跳过已经存在的文件?