当前位置: 首页 > 知识库问答 >
问题:

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

欧阳衡
2023-03-14

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

共有1个答案

百里丁雨
2023-03-14

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

这个方法将允许您执行一些后台进程,同时更新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" />

这里的大问题是:我如何从一个服务更新我的activity?。在下一个示例中,我们将使用两个您可能不知道的类:resultreceiverintentserviceresultreceiver允许我们从服务更新线程;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);
    }
}

将服务添加到清单:

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

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

Groundy用于下载文件并显示进度的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;
        }
    }
}

并将其添加到清单中:

<service android:name="com.codeslap.groundy.GroundyService"/>

我想这是再容易不过了。只需从Github获取最新的jar,您就可以开始了。请记住,Groundy的主要目的是在后台服务中调用外部REST API并轻松地将结果发布到UI。如果你在你的应用程序中做这样的事情,它可能真的很有用。

GingerBread带来了一个新特性,downloadManager,它允许您轻松下载文件,并将处理线程、流等的辛苦工作委托给系统

先来看一个实用方法:

/**
 * @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);

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

第一和第二种方法只是冰山一角。如果你想要你的应用程序健壮,有很多事情你必须记住。这里简单列举一下:

  • 必须检查用户是否有可用的internet连接
  • 确保您具有正确的权限(internetwrite_external_storage);如果要检查internet可用性,还应使用access_network_state
  • 确保要下载文件的目录存在并且具有写入权限。
  • 如果下载太大,您可能需要实现一种方法,以便在以前的尝试失败时恢复下载。
  • 如果您允许用户中断下载,他们将不胜感激。

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

但也要考虑到您的需求可能会发生变化。例如,downloadmanager不执行响应缓存。它会盲目地多次下载同一个大文件。事后没有简单的办法来解决它。其中,如果您从一个基本的HttpURLConnection(1,2)开始,那么您所需要的只是添加一个HttpResponSecache。因此,学习基本的、标准的工具的最初努力可以是一个很好的投资。

API level 26中不推荐使用此类。ProgressDialog是一个模式对话框,它阻止用户与应用程序交互。与其使用这个类,不如使用ProgressBar这样的进度指示器,它可以嵌入到应用程序的UI中。或者,您可以使用通知来通知用户任务的进度。有关更多详细信息链接

 类似资料:
  • 本文向大家介绍Python HTTP下载文件并显示下载进度条功能的实现,包括了Python HTTP下载文件并显示下载进度条功能的实现的使用技巧和注意事项,需要的朋友参考一下 下面的Python脚本中利用request下载文件并写入到文件系统,利用progressbar模块显示下载进度条。 其中利用request模块下载文件可以直接下载,不需要使用open方法,例如: 下面的例子是题目中完整的例子

  • 问题内容: 我目前有一个班级,应该在下载文件时向我展示一个简单的表格。它正在工作,但是进度条没有更新,下载完成后我只能看到它。有人能帮我吗? 问题答案: 您的是经典的Swing并发问题。解决方案始终如一-在后台线程中运行长时间的代码,例如可以在SwingWorker中找到的代码。 例如,

  • 本文向大家介绍Android使用AsyncTask下载图片并显示进度条功能,包括了Android使用AsyncTask下载图片并显示进度条功能的使用技巧和注意事项,需要的朋友参考一下 在Android中实现异步任务机制有两种方式,Handler和AsyncTask。这篇文章给大家介绍Android使用AsyncTask下载图片并显示进度条功能。 AsyncTask下载图片并显示下载进度,异步类As

  • 问题内容: 我正在尝试使用Ajax下载文件并显示自定义 下载进度栏。 问题是我不知道该怎么做。我编写了用于记录进度的代码,但不知道如何启动下载。 注意: 文件是不同类型的。 提前致谢。 JS HTML和PHP 问题答案: 如果要向用户显示下载过程的进度条,则必须在xmlhttprequest中进行下载。这里的问题之一是,如果您的文件很大-它们将被保存 在 浏览器 的内存 中,然后浏览器会将它们写入

  • 本文向大家介绍C# Winform下载文件并显示进度条的实现代码,包括了C# Winform下载文件并显示进度条的实现代码的使用技巧和注意事项,需要的朋友参考一下 方法一: 效果如下图所示: 代码如下: 实现方法二: WinForm下载文件并显示下载进度示例

  • 本文向大家介绍Android Retrofit文件下载进度显示问题的解决方法,包括了Android Retrofit文件下载进度显示问题的解决方法的使用技巧和注意事项,需要的朋友参考一下 综述   在Retrofit2.0使用详解这篇文章中详细介绍了retrofit的用法。并且在retrofit中我们可以通过ResponseBody进行对文件的下载。但是在retrofit中并没有为我们提供显示下载