java - 使用 Android 下载文件,并在 ProgressDialog 中显示进度

标签 java android download android-asynctask

我正在尝试编写一个可以更新的简单应用程序。为此,我需要一个可以下载文件并在 ProgressDialog 中显示当前进度的简单函数。 .我知道怎么做ProgressDialog ,但我不确定如何显示当前进度以及如何首先下载文件。

最佳答案

下载文件的方法有很多种。下面我将发布最常见的方式;由您决定哪种方法更适合您的应用程序。

1.使用AsyncTask并在对话框中显示下载进度

此方法将允许您同时执行一些后台进程并更新 UI(在本例中,我们将更新进度条)。

进口:

import android.os.PowerManager;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.net.HttpURLConnection;

这是一个示例代码:
// declare the dialog as a member field of your activity
ProgressDialog mProgressDialog;

// instantiate it within the onCreate method
mProgressDialog = new ProgressDialog(YourActivity.this);
mProgressDialog.setMessage("A message");
mProgressDialog.setIndeterminate(true);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(true);

// execute this when the downloader must be fired
final DownloadTask downloadTask = new DownloadTask(YourActivity.this);
downloadTask.execute("the url to the file you want to download");

mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {

    @Override
    public void onCancel(DialogInterface dialog) {
        downloadTask.cancel(true); //cancel the task
    }
});
AsyncTask看起来像这样:
// usually, subclasses of AsyncTask are declared inside the activity class.
// that way, you can easily modify the UI thread from here
private class DownloadTask extends AsyncTask<String, Integer, String> {

    private Context context;
    private PowerManager.WakeLock mWakeLock;

    public DownloadTask(Context context) {
        this.context = context;
    }

    @Override
    protected String doInBackground(String... sUrl) {
        InputStream input = null;
        OutputStream output = null;
        HttpURLConnection connection = null;
        try {
            URL url = new URL(sUrl[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();

            // expect HTTP 200 OK, so we don't mistakenly save error report
            // instead of the file
            if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                return "Server returned HTTP " + connection.getResponseCode()
                        + " " + connection.getResponseMessage();
            }

            // this will be useful to display download percentage
            // might be -1: server did not report the length
            int fileLength = connection.getContentLength();

            // download the file
            input = connection.getInputStream();
            output = new FileOutputStream("/sdcard/file_name.extension");

            byte data[] = new byte[4096];
            long total = 0;
            int count;
            while ((count = input.read(data)) != -1) {
                // allow canceling with back button
                if (isCancelled()) {
                    input.close();
                    return null;
                }
                total += count;
                // publishing the progress....
                if (fileLength > 0) // only if total length is known
                    publishProgress((int) (total * 100 / fileLength));
                output.write(data, 0, count);
            }
        } catch (Exception e) {
            return e.toString();
        } finally {
            try {
                if (output != null)
                    output.close();
                if (input != null)
                    input.close();
            } catch (IOException ignored) {
            }

            if (connection != null)
                connection.disconnect();
        }
        return null;
    }

上面的方法 ( doInBackground ) 总是在后台线程上运行。你不应该在那里做任何 UI 任务。另一方面,onProgressUpdateonPreExecute在 UI 线程上运行,因此您可以在那里更改进度条:
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // take CPU lock to prevent CPU from going off if the user 
        // presses the power button during download
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
             getClass().getName());
        mWakeLock.acquire();
        mProgressDialog.show();
    }

    @Override
    protected void onProgressUpdate(Integer... progress) {
        super.onProgressUpdate(progress);
        // if we get here, length is known, now set indeterminate to false
        mProgressDialog.setIndeterminate(false);
        mProgressDialog.setMax(100);
        mProgressDialog.setProgress(progress[0]);
    }

    @Override
    protected void onPostExecute(String result) {
        mWakeLock.release();
        mProgressDialog.dismiss();
        if (result != null)
            Toast.makeText(context,"Download error: "+result, Toast.LENGTH_LONG).show();
        else
            Toast.makeText(context,"File downloaded", Toast.LENGTH_SHORT).show();
    }

为此,您需要 WAKE_LOCK 权限。
<uses-permission android:name="android.permission.WAKE_LOCK" />

2. 从服务下载

这里的大问题是:如何从服务更新我的 Activity ?。在下一个示例中,我们将使用两个您可能不知道的类:ResultReceiverIntentService . ResultReceiver是允许我们从服务更新线程的那个; IntentServiceService 的子类它产生一个线程来从那里做后台工作(你应该知道 Service 实际上在你的应用程序的同一个线程中运行;当你扩展 Service 时,你必须手动产生新线程来运行 CPU 阻塞操作)。

下载服务看起来像这样:
public class DownloadService extends IntentService {
    public static final int UPDATE_PROGRESS = 8344;

    public DownloadService() {
        super("DownloadService");
    }
    @Override
    protected void onHandleIntent(Intent intent) {

        String urlToDownload = intent.getStringExtra("url");
        ResultReceiver receiver = (ResultReceiver) intent.getParcelableExtra("receiver");
        try {

            //create url and connect
            URL url = new URL(urlToDownload);
            URLConnection connection = url.openConnection();
            connection.connect();

            // this will be useful so that you can show a typical 0-100% progress bar
            int fileLength = connection.getContentLength();

            // download the file
            InputStream input = new BufferedInputStream(connection.getInputStream());

            String path = "/sdcard/BarcodeScanner-debug.apk" ;
            OutputStream output = new FileOutputStream(path);

            byte data[] = new byte[1024];
            long total = 0;
            int count;
            while ((count = input.read(data)) != -1) {
                total += count;

                // publishing the progress....
                Bundle resultData = new Bundle();
                resultData.putInt("progress" ,(int) (total * 100 / fileLength));
                receiver.send(UPDATE_PROGRESS, resultData);
                output.write(data, 0, count);
            }

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

        } catch (IOException e) {
            e.printStackTrace();
        }

        Bundle resultData = new Bundle();
        resultData.putInt("progress" ,100);

        receiver.send(UPDATE_PROGRESS, resultData);
    }
}

将服务添加到您的 list 中:
<service android:name=".DownloadService"/>

Activity 将如下所示:
// initialize the progress dialog like in the first example

// this is how you fire the downloader
mProgressDialog.show();
Intent intent = new Intent(this, DownloadService.class);
intent.putExtra("url", "url of the file to download");
intent.putExtra("receiver", new DownloadReceiver(new Handler()));
startService(intent);

这是ResultReceiver来玩:
private class DownloadReceiver extends ResultReceiver{

    public DownloadReceiver(Handler handler) {
        super(handler);
    }

    @Override
    protected void onReceiveResult(int resultCode, Bundle resultData) {

        super.onReceiveResult(resultCode, resultData);

        if (resultCode == DownloadService.UPDATE_PROGRESS) {

            int progress = resultData.getInt("progress"); //get the progress
            dialog.setProgress(progress);

            if (progress == 100) {
                dialog.dismiss();
            }
        }
    }
}

2.1 使用 Groundy 库

Groundy是一个基本上可以帮助您在后台服务中运行代码段的库,它基于 ResultReceiver概念如上所示。这个库是 已弃用 在这一刻。 是这样的整体代码如下:

您在其中显示对话框的 Activity ...
public class MainActivity extends Activity {

    private ProgressDialog mProgressDialog;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        findViewById(R.id.btn_download).setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                String url = ((EditText) findViewById(R.id.edit_url)).getText().toString().trim();
                Bundle extras = new Bundler().add(DownloadTask.PARAM_URL, url).build();
                Groundy.create(DownloadExample.this, DownloadTask.class)
                        .receiver(mReceiver)
                        .params(extras)
                        .queue();

                mProgressDialog = new ProgressDialog(MainActivity.this);
                mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                mProgressDialog.setCancelable(false);
                mProgressDialog.show();
            }
        });
    }

    private ResultReceiver mReceiver = new ResultReceiver(new Handler()) {
        @Override
        protected void onReceiveResult(int resultCode, Bundle resultData) {
            super.onReceiveResult(resultCode, resultData);
            switch (resultCode) {
                case Groundy.STATUS_PROGRESS:
                    mProgressDialog.setProgress(resultData.getInt(Groundy.KEY_PROGRESS));
                    break;
                case Groundy.STATUS_FINISHED:
                    Toast.makeText(DownloadExample.this, R.string.file_downloaded, Toast.LENGTH_LONG);
                    mProgressDialog.dismiss();
                    break;
                case Groundy.STATUS_ERROR:
                    Toast.makeText(DownloadExample.this, resultData.getString(Groundy.KEY_ERROR), Toast.LENGTH_LONG).show();
                    mProgressDialog.dismiss();
                    break;
            }
        }
    };
}

一个 GroundyTask 使用的实现接地气 下载文件并显示进度:
public class DownloadTask extends GroundyTask {    
    public static final String PARAM_URL = "com.groundy.sample.param.url";

    @Override
    protected boolean doInBackground() {
        try {
            String url = getParameters().getString(PARAM_URL);
            File dest = new File(getContext().getFilesDir(), new File(url).getName());
            DownloadUtils.downloadFile(getContext(), url, dest, DownloadUtils.getDownloadListenerForTask(this));
            return true;
        } catch (Exception pokemon) {
            return false;
        }
    }
}

只需将其添加到 list 中:
<service android:name="com.codeslap.groundy.GroundyService"/>

我想这再简单不过了。只需获取最新的 jar from Github你准备好了。请记住,接地气 的主要目的是在后台服务中调用外部 REST api,并轻松地将结果发布到 UI。如果你在你的应用程序中做类似的事情,它可能真的很有用。

2.2 使用https://github.com/koush/ion

3.使用DownloadManager类(仅 GingerBread 和更新版本)

GingerBread 带来了一个新功能,DownloadManager ,它允许您轻松下载文件并将处理线程、流等的繁重工作委托(delegate)给系统。

首先,让我们看看一个实用方法:
/**
 * @param context used to check the device version and DownloadManager information
 * @return true if the download manager is available
 */
public static boolean isDownloadManagerAvailable(Context context) {

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
        return true;
    }
    return false;
}

方法的名称说明了一切。一旦你确定 DownloadManager可用,您可以执行以下操作:
String url = "url you want to download";
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setDescription("Some descrition");
request.setTitle("Some title");
// in order for this if to run, you must use the android 3.2 to compile your app
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
    request.allowScanningByMediaScanner();
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "name-of-the-file.ext");

// get download service and enqueue file
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);

下载进度将显示在通知栏中。

最后的想法

第一种和第二种方法只是冰山一角。如果您希望您的应用程序健壮,您必须记住很多事情。这是一个简短的列表:
  • 您必须检查用户是否有可用的互联网连接
  • 确保您拥有正确的权限( INTERNETWRITE_EXTERNAL_STORAGE );还有ACCESS_NETWORK_STATE如果您想检查互联网可用性。
  • 确保您要下载文件的目录存在并且具有写入权限。
  • 如果下载太大,您可能需要实现一种在之前尝试失败的情况下恢复下载的方法。
  • 如果您允许他们中断下载,用户将不胜感激。

  • 除非您需要对下载过程进行详细控制,否则可以考虑使用 DownloadManager (3) 因为它已经处理了上面列出的大部分项目。

    但也要考虑到您的需求可能会发生变化。例如,DownloadManager does no response caching .它会盲目地多次下载同一个大文件。事后没有简单的方法来修复它。如果你从一个基本的开始 HttpURLConnection (1, 2),那么你只需要添加一个 HttpResponseCache .因此,最初学习基本标准工具的努力可能是一项不错的投资。

    This class was deprecated in API level 26. ProgressDialog is a modal dialog, which prevents the user from interacting with the app. Instead of using this class, you should use a progress indicator like ProgressBar, which can be embedded in your app's UI. Alternatively, you can use a notification to inform the user of the task's progress. For more details Link

    关于java - 使用 Android 下载文件,并在 ProgressDialog 中显示进度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3028306/

    相关文章:

    java - 抛出异常时 IT 测试不会失败 Arquillian TestNG maven

    java - 映射到 com.vividsolutions.jts.geom.Point 无效的字节序标志

    java - Spring-ws客户端mtom

    android - 提取文本的用例

    多次触发 Scrollview 的 Android onScrollChanged

    asp.net - 在 ASP.NET 中下载文本文件是附加网页 HTML

    java - 从 MQSeries 读取/写入字符字节

    python - 如何仅下载数据 Python 的前 x 个字节

    javascript - R中的Download.file函数和手动下载

    c# - 向表格单元格Android添加随机值