使用 AsyncTask 下载文件 [英] Download file with AsyncTask

查看:30
本文介绍了使用 AsyncTask 下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 asyncTask 下载文件,但无法正常工作,没有错误消息或什么也没有,只是不要下载文件...我尝试了所有方法,但似乎暂时没有进入...任何人知道可能是什么问题吗?我在我的手机上测试过,网址也可以.

I am trying to download a file with asyncTask but is not working, there is no error messages or nothing, just dont download the file... i try everything but it appears that is not entering on the while... anybody know what can be the problem? I tested on my mobile, the url is ok too.

class DownloadFileFromURL extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        System.out.println("Starting download");
    }

    /**
     * Downloading file in background thread
     * */
    @Override
    protected String doInBackground(String... f_url) {
        int count;
        try {
            String root = Environment.getExternalStorageDirectory().toString();

            System.out.println("Downloading");
            URL url = new URL(f_url[0]);

            URLConnection conection = url.openConnection();
            conection.connect();
            // getting file length
            int lenghtOfFile = conection.getContentLength();

            // input stream to read file - with 8k buffer
            InputStream input = new BufferedInputStream(url.openStream(), 8192);

            // Output stream to write file

            OutputStream output = new         FileOutputStream(root+"/downloadedfile.jpg");
            byte data[] = new byte[1024];

            long total = 0;
            while ((count = input.read(data)) != -1) {
                total += count;

                // writing data to file
                output.write(data, 0, count);

            }

            // flushing output
            output.flush();

            // closing streams
            output.close();
            input.close();

        } catch (Exception e) {
            Log.e("Error: ", e.getMessage());
        }

        return null;
    }



    /**
     * After completing background task
     * **/
    @Override
    protected void onPostExecute(String file_url) {
       System.out.println("Downloaded");
    }

}

推荐答案

我刚刚运行了你的代码,它对我来说很好.图像已下载到 SD 卡.

I just ran your code, and it works fine for me. The image was downloaded to the sdcard.

请注意,请确保您在 AndroidManifest.xml 中设置了这些权限:

Just to note, make sure you have these permissions set in your AndroidManifest.xml:

<uses-permission android:name="android.permission.INTERNET" />

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

这是我得到的日志(注意我添加了一个ProgressDialog):

Here are the logs I got (note that I added a ProgressDialog):

03-21 16:53:46.422  21017-21017/com.imagedownload.danielnugent.imagedownload D/Activity﹕ #1 setTransGradationModeColor false
03-21 16:53:56.211  21017-21017/com.imagedownload.danielnugent.imagedownload D/Activity﹕ #1 setTransGradationModeColor false
03-21 16:54:06.441  21017-21017/com.imagedownload.danielnugent.imagedownload I/System.out﹕ Starting download
03-21 16:54:06.441  21017-21017/com.imagedownload.danielnugent.imagedownload D/Dialog﹕ checkMirrorLinkEnabled returns : false
03-21 16:54:06.441  21017-21017/com.imagedownload.danielnugent.imagedownload D/Dialog﹕ showing allowed
03-21 16:54:06.461  21017-25126/com.imagedownload.danielnugent.imagedownload I/System.out﹕ Downloading
03-21 16:54:06.461  21017-21017/com.imagedownload.danielnugent.imagedownload D/Activity﹕ #1 setTransGradationModeColor false
03-21 16:54:06.481  21017-21017/com.imagedownload.danielnugent.imagedownload D/ProgressBar﹕ updateDrawableBounds: left = 0
03-21 16:54:06.481  21017-21017/com.imagedownload.danielnugent.imagedownload D/ProgressBar﹕ updateDrawableBounds: top = 0
03-21 16:54:06.491  21017-21017/com.imagedownload.danielnugent.imagedownload D/ProgressBar﹕ updateDrawableBounds: right = 144
03-21 16:54:06.491  21017-21017/com.imagedownload.danielnugent.imagedownload D/ProgressBar﹕ updateDrawableBounds: bottom = 144
03-21 16:54:11.596  21017-21017/com.imagedownload.danielnugent.imagedownload I/System.out﹕ Downloaded

以防万一这会有用,这里是对我有用的完整 MainActivity.java 代码.(url 是占位符):

Just in case this will be useful, here is the full MainActivity.java code that worked for me. (url is a placeholder):

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Environment;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;


public class MainActivity extends ActionBarActivity {

    private ProgressDialog pDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        new DownloadFileFromURL().execute("http://www.example.com/IMG.jpg");
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    class DownloadFileFromURL extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            System.out.println("Starting download");

            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Loading... Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        /**
         * Downloading file in background thread
         * */
        @Override
        protected String doInBackground(String... f_url) {
            int count;
            try {
                String root = Environment.getExternalStorageDirectory().toString();

                System.out.println("Downloading");
                URL url = new URL(f_url[0]);

                URLConnection conection = url.openConnection();
                conection.connect();
                // getting file length
                int lenghtOfFile = conection.getContentLength();

                // input stream to read file - with 8k buffer
                InputStream input = new BufferedInputStream(url.openStream(), 8192);

                // Output stream to write file

                OutputStream output = new FileOutputStream(root+"/downloadedfile.jpg");
                byte data[] = new byte[1024];

                long total = 0;
                while ((count = input.read(data)) != -1) {
                    total += count;

                    // writing data to file
                    output.write(data, 0, count);

                }

                // flushing output
                output.flush();

                // closing streams
                output.close();
                input.close();

            } catch (Exception e) {
                Log.e("Error: ", e.getMessage());
            }

            return null;
        }



        /**
         * After completing background task
         * **/
        @Override
        protected void onPostExecute(String file_url) {
            System.out.println("Downloaded");

            pDialog.dismiss();
        }

    }

}

这篇关于使用 AsyncTask 下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆