2

我在使用 android 4.0 或更高版本时遇到问题,我试图从 URL 下载文件,它在 android Galaxy Y 2.3 / 2.2 中运行良好,但是当我对 Galaxy S3(4.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());
    }
}

Obs:没有错误,它只是开始下载并停止它。文件大小:126,188 字节,在 Galaxy S3 中为 6,403 字节

4

2 回答 2

2

使用AsyncTask提出您的请求。

AsyncTask 允许正确和轻松地使用 UI 线程。此类允许在 UI 线程上执行后台操作并发布结果,而无需操作线程和/或处理程序。

于 2013-01-14T18:00:06.090 回答
1

您可能在主线程上进行网络操作,StrictMode 不允许这样做。

于 2013-01-14T18:39:55.770 回答