【问题标题】:Download a file with Android, and showing the progress in a ProgressDialog使用 Android 下载文件,并在 ProgressDialog 中显示进度
【发布时间】:2016-12-30 01:49:56
【问题描述】:

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

【问题讨论】:

标签: java android download android-asynctask


【解决方案1】:

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

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。从服务下载

这里最大的问题是:如何从服务更新我的活动?。在下一个示例中,我们将使用您可能不知道的两个类: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"/>

活动将如下所示:

// 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 概念。该库目前已弃用。这就是整个代码的样子:

您正在显示对话框的活动...

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"/>

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

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

3。使用DownloadManager 类(仅限GingerBread 和更高版本)

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

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

最后的想法

第一种和第二种方法只是冰山一角。如果您希望您的应用程序健壮,您必须记住很多事情。这是一个简短的列表:

  • 您必须检查用户是否有可用的互联网连接
  • 确保您拥有正确的权限(INTERNETWRITE_EXTERNAL_STORAGE);如果您想检查互联网可用性,也可以ACCESS_NETWORK_STATE
  • 确保您要下载文件的目录存在并且具有写入权限。
  • 如果下载过大,您可能需要实施一种方法来在之前的尝试失败时恢复下载。
  • 如果您允许用户中断下载,用户将不胜感激。

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

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

此类在 API 级别 26 中已弃用。ProgressDialog 是一种模式 对话框,它会阻止用户与应用程序交互。反而 使用此类,您应该使用进度指示器,例如 ProgressBar,可以嵌入到应用程序的 UI 中。或者, 您可以使用通知来通知用户任务的进度。更多详情Link

【讨论】:

  • DownloadManager 是操作系统的一部分,这意味着它在 GB+ 中始终可用且无法卸载。
  • 克里斯蒂安的回答有问题。因为“1. 使用 AsyncTask 并在对话框中显示下载进度”处的代码执行 connection.connect();然后 InputStream 输入 = new BufferedInputStream(url.openStream());代码与服务器建立 2 个连接。我已经设法通过如下更新代码来改变这种行为 InputStream input = new BufferedInputStream(connection.getInputStream());
  • 我希望 android 文档能这么简洁。
  • 建议close()finally中的流(output)而不是try,否则如果在close()之前抛出任何异常,你有未关闭的流挂起周围。
  • 不要硬编码 /sdcard/ 改用Environment.getExternalStorageDirectory()
【解决方案2】:

如果您要从 Internet 下载内容,请不要忘记为您的清单文件添加权限!

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.helloandroid"
    android:versionCode="1"
    android:versionName="1.0">

        <uses-sdk android:minSdkVersion="10" />

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

        <application 
            android:icon="@drawable/icon" 
            android:label="@string/app_name" 
            android:debuggable="true">

        </application>

</manifest>

【讨论】:

  • 我很确定你不需要 READ_PHONE_STATE 并且你绝对不需要 WRITE_EXTERNAL_STORAGE;这是一个危险的权限,可以通过使用存储访问框架来避免。
【解决方案3】:

是的,上面的代码将起作用。但是如果您在 onProgressUpdateAsynctask 中更新您的 progressbar,并且您按下后退按钮或完成您的活动,AsyncTask 会在您的 UI 中失去它的轨道。当您离开时回到您的活动,即使下载在后台运行,您也不会在进度条上看到任何更新。所以在OnResume() 上尝试运行一个类似runOnUIThread 的线程,并使用一个定时器任务更新你的progressbar,并使用从AsyncTask 运行背景更新的值。

private void updateProgressBar(){
    Runnable runnable = new updateProgress();
    background = new Thread(runnable);
    background.start();
}

public class updateProgress implements Runnable {
    public void run() {
        while(Thread.currentThread()==background)
            //while (!Thread.currentThread().isInterrupted()) {
            try {
                Thread.sleep(1000); 
                Message msg = new Message();
                progress = getProgressPercentage();        
                handler.sendMessage(msg);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            } catch (Exception e) {
        }
    }
}

private Handler handler = new Handler(){
    @Override
    public void handleMessage(Message msg) {
        progress.setProgress(msg.what);
    }
};

当你的活动不可见时,不要忘记销毁线程。

private void destroyRunningThreads() {
    if (background != null) {
        background.interrupt();
        background=null;
    }
}

【讨论】:

  • 这正是我的问题。你能告诉我如何做一个定时器任务来更新进度条吗?如何从后面运行的 AsyncTask 获取值更新
  • okk 将全局或静态变量带到从异步任务更新您的值的位置...或者您可以将其插入数据库中以确保安全...这样关闭应用程序不会妨碍..当您重新启动时您想要更新您的 UI 的活动运行 UI 线程。请参见下面的示例
  • UI 应该有新的参考......就像我的情况下新初始化的 ProgressBar
  • @sheetal,但是没有你的代码它也能正常工作!为什么?!我的设备是装有 Android 4.0.4 的 Xperia P。我已经定义了一个静态布尔变量,onPreExecute 将其设置为 true,而 onPostExecute 将其设置为 false。它显示我们是否正在下载,因此我们可以检查变量是否等于true,显示之前的进度条对话框。
  • @sheetal 你的代码有点晦涩难懂,能给我一些建议吗?
【解决方案4】:

我建议你使用我的项目Netroid,它基于Volley。我为其添加了一些功能,例如多事件回调,文件下载管理。这可能会有所帮助。

【讨论】:

  • 支持多文件下载吗?我正在开发一个允许用户按计划下载的项目。在特定时间(例如上午 12 点),该服务将下载用户之前选择的所有链接。我的意思是我需要的服务必须能够排队下载链接,然后下载所有链接(一个接一个或并行,取决于用户)。谢谢
  • @piavgh 是的,你想要的只是满足,你可以查看我的示例 apk,它包含一个文件下载管理演示。
  • 很棒的图书馆!效果很好,尽管我在从 HTTPS 网址下载内容时遇到问题,因为虽然可以设置自己的 SSLSocketFactory 添加HostnameVerifier 是不可能的,我需要这样的验证程序。对此提出了issue
  • Volley. 的链接 -> 未找到
【解决方案5】:

我已经修改了AsyncTask 类以处理在同一上下文中创建progressDialog。我认为以下代码将更可重用。 (它可以从任何活动中调用,只需传递上下文、目标文件、对话框消息)

public static class DownloadTask extends AsyncTask<String, Integer, String> {
    private ProgressDialog mPDialog;
    private Context mContext;
    private PowerManager.WakeLock mWakeLock;
    private File mTargetFile;
    //Constructor parameters :
    // @context (current Activity)
    // @targetFile (File object to write,it will be overwritten if exist)
    // @dialogMessage (message of the ProgresDialog)
    public DownloadTask(Context context,File targetFile,String dialogMessage) {
        this.mContext = context;
        this.mTargetFile = targetFile;
        mPDialog = new ProgressDialog(context);

        mPDialog.setMessage(dialogMessage);
        mPDialog.setIndeterminate(true);
        mPDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mPDialog.setCancelable(true);
        // reference to instance to use inside listener
        final DownloadTask me = this;
        mPDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                me.cancel(true);
            }
        });
        Log.i("DownloadTask","Constructor done");
    }

    @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();
            }
            Log.i("DownloadTask","Response " + connection.getResponseCode());

            // 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(mTargetFile,false);

            byte data[] = new byte[4096];
            long total = 0;
            int count;
            while ((count = input.read(data)) != -1) {
                // allow canceling with back button
                if (isCancelled()) {
                    Log.i("DownloadTask","Cancelled");
                    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;
    }
    @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) mContext.getSystemService(Context.POWER_SERVICE);
        mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                getClass().getName());
        mWakeLock.acquire();

        mPDialog.show();

    }

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

    }

    @Override
    protected void onPostExecute(String result) {
        Log.i("DownloadTask", "Work Done! PostExecute");
        mWakeLock.release();
        mPDialog.dismiss();
        if (result != null)
            Toast.makeText(mContext,"Download error: "+result, Toast.LENGTH_LONG).show();
        else
            Toast.makeText(mContext,"File Downloaded", Toast.LENGTH_SHORT).show();
    }
}

【讨论】:

  • 别忘了添加唤醒锁权限
  • publishProgress 方法从何而来?
【解决方案6】:

我发现this的博文很有帮助,它使用loopJ来下载文件,它只有一个简单的功能,对一些新的android人会有帮助。

【讨论】:

    【解决方案7】:

    不要忘记用 new File("/mnt/sdcard/...") 替换 "/sdcard..." 否则你会得到一个 FileNotFoundException

    【讨论】:

    • 在第 2 部分从服务下载进度对话框无法显示进度增量。它直接返回 100,所以如果 100 它直接检查 setprogress 100 并进度结束,如何增加进度??它只显示 0 进度但实际下载正在运行
    • 它只显示 0% 的 100 只其他正常工作
    • 不要这样做!有 Environment.getExternalStorageDirectory().getAbsolutePath() 用于获取 sdcard 的路径。另外不要忘记检查外部存储是否已安装 - Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) (Mannaz)
    【解决方案8】:

    当我开始学习 android 开发时,我了解到ProgressDialog 是要走的路。 ProgressDialogsetProgress 方法可以在文件下载时被调用以更新进度级别。

    我在许多应用程序中看到的最好的一点是,它们自定义了此进度对话框的属性,以便为进度对话框提供比普通版本更好的外观和感觉。很好地让用户参与一些像青蛙、大象或可爱的猫/小狗这样的动画。进度对话框中的任何动画都会吸引用户,他们不会觉得等待太久。

    【解决方案9】:

    我的个人建议是使用进度对话框并在执行前建立,或者在OnPreExecute()发起,如果你使用进度对话框的进度条的水平样式,请经常发布进度。剩下的就是优化doInBackground的算法了。

    【讨论】:

      【解决方案10】:

      使用 Android Query 库,确实很酷。您可以将其更改为使用 ProgressDialog,就像您在其他示例中看到的那样,这将显示您布局中的进度视图并在完成后将其隐藏。

      File target = new File(new File(Environment.getExternalStorageDirectory(), "ApplicationName"), "tmp.pdf");
      new AQuery(this).progress(R.id.progress_view).download(_competition.qualificationScoreCardsPdf(), target, new AjaxCallback<File>() {
          public void callback(String url, File file, AjaxStatus status) {
              if (file != null) {
                  // do something with file  
              } 
          }
      });
      

      【讨论】:

      • 问题是,我停止使用它,因为它没有维护所以不要再认为这是一个好的答案。
      【解决方案11】:

      我们可以使用协程和工作管理器在kotlin中下载文件。

      在 build.gradle 中添加依赖

          implementation "androidx.work:work-runtime-ktx:2.3.0-beta01"
          implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.1"
      

      WorkManager 类

          import android.content.Context
          import android.os.Environment
          import androidx.work.CoroutineWorker
          import androidx.work.WorkerParameters
          import androidx.work.workDataOf
          import com.sa.chat.utils.Const.BASE_URL_IMAGE
          import com.sa.chat.utils.Constants
          import kotlinx.coroutines.delay
          import java.io.BufferedInputStream
          import java.io.File
          import java.io.FileOutputStream
          import java.net.URL
      
          class DownloadMediaWorkManager(appContext: Context, workerParams: WorkerParameters)
              : CoroutineWorker(appContext, workerParams) {
      
              companion object {
                  const val WORK_TYPE = "WORK_TYPE"
                  const val WORK_IN_PROGRESS = "WORK_IN_PROGRESS"
                  const val WORK_PROGRESS_VALUE = "WORK_PROGRESS_VALUE"
              }
      
              override suspend fun doWork(): Result {
      
                  val imageUrl = inputData.getString(Constants.WORK_DATA_MEDIA_URL)
                  val imagePath = downloadMediaFromURL(imageUrl)
      
                  return if (!imagePath.isNullOrEmpty()) {
                      Result.success(workDataOf(Constants.WORK_DATA_MEDIA_URL to imagePath))
                  } else {
                      Result.failure()
                  }
              }
      
              private suspend fun downloadMediaFromURL(imageUrl: String?): String? {
      
                  val file = File(
                          getRootFile().path,
                          "IMG_${System.currentTimeMillis()}.jpeg"
                  )
      
                  val url = URL(BASE_URL_IMAGE + imageUrl)
                  val connection = url.openConnection()
                  connection.connect()
      
                  val lengthOfFile = connection.contentLength
                  // download the file
                  val input = BufferedInputStream(url.openStream(), 8192)
                  // Output stream
                  val output = FileOutputStream(file)
      
                  val data = ByteArray(1024)
                  var total: Long = 0
                  var last = 0
      
                  while (true) {
      
                      val count = input.read(data)
                      if (count == -1) break
                      total += count.toLong()
      
                      val progress = (total * 100 / lengthOfFile).toInt()
      
                      if (progress % 10 == 0) {
                          if (last != progress) {
                              setProgress(workDataOf(WORK_TYPE to WORK_IN_PROGRESS,
                                      WORK_PROGRESS_VALUE to progress))
                          }
                          last = progress
                          delay(50)
                      }
                      output.write(data, 0, count)
                  }
      
                  output.flush()
                  output.close()
                  input.close()
      
                  return file.path
      
              }
      
              private fun getRootFile(): File {
      
                  val rootDir = File(Environment.getExternalStorageDirectory().absolutePath + "/AppName")
      
                  if (!rootDir.exists()) {
                      rootDir.mkdir()
                  }
      
                  val dir = File("$rootDir/${Constants.IMAGE_FOLDER}/")
      
                  if (!dir.exists()) {
                      dir.mkdir()
                  }
                  return File(dir.absolutePath)
              }
          }
      

      通过activity类中的工作管理器开始下载

       private fun downloadImage(imagePath: String?, id: String) {
      
                  val data = workDataOf(WORK_DATA_MEDIA_URL to imagePath)
                  val downloadImageWorkManager = OneTimeWorkRequestBuilder<DownloadMediaWorkManager>()
                          .setInputData(data)
                          .addTag(id)
                          .build()
      
                  WorkManager.getInstance(this).enqueue(downloadImageWorkManager)
      
                  WorkManager.getInstance(this).getWorkInfoByIdLiveData(downloadImageWorkManager.id)
                          .observe(this, Observer { workInfo ->
      
                              if (workInfo != null) {
                                  when {
                                      workInfo.state == WorkInfo.State.SUCCEEDED -> {
                                          progressBar?.visibility = View.GONE
                                          ivDownload?.visibility = View.GONE
                                      }
                                      workInfo.state == WorkInfo.State.FAILED || workInfo.state == WorkInfo.State.CANCELLED || workInfo.state == WorkInfo.State.BLOCKED -> {
                                          progressBar?.visibility = View.GONE
                                          ivDownload?.visibility = View.VISIBLE
                                      }
                                      else -> {
                                          if(workInfo.progress.getString(WORK_TYPE) == WORK_IN_PROGRESS){
                                              val progress = workInfo.progress.getInt(WORK_PROGRESS_VALUE, 0)
                                              progressBar?.visibility = View.VISIBLE
                                              progressBar?.progress = progress
                                              ivDownload?.visibility = View.GONE
      
                                          }
                                      }
                                  }
                              }
                          })
      
              }
      

      【讨论】:

        【解决方案12】:

        权限

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

        使用 HttpURLConnection

        import java.io.File;
        import java.io.FileOutputStream;
        import java.io.IOException;
        import java.io.InputStream;
        import java.net.HttpURLConnection;
        import java.net.MalformedURLException;
        import java.net.URL;
        
        import android.app.Activity;
        import android.app.Dialog;
        import android.os.Bundle;
        import android.os.Environment;
        import android.view.View;
        import android.view.Window;
        import android.view.View.OnClickListener;
        import android.widget.Button;
        import android.widget.ProgressBar;
        import android.widget.TextView;
        import android.widget.Toast;
        
        public class DownloadFileUseHttpURLConnection extends Activity {
        
        ProgressBar pb;
        Dialog dialog;
        int downloadedSize = 0;
        int totalSize = 0;
        TextView cur_val;
        String dwnload_file_path =  
        "http://coderzheaven.com/sample_folder/sample_file.png";
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
        
            Button b = (Button) findViewById(R.id.b1);
            b.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                     showProgress(dwnload_file_path);
        
                        new Thread(new Runnable() {
                            public void run() {
                                 downloadFile();
                            }
                          }).start();
                }
            });
        }
        
        void downloadFile(){
        
            try {
                URL url = new URL(dwnload_file_path);
                HttpURLConnection urlConnection = (HttpURLConnection)   
         url.openConnection();
        
                urlConnection.setRequestMethod("GET");
                urlConnection.setDoOutput(true);
        
                //connect
                urlConnection.connect();
        
                //set the path where we want to save the file           
                File SDCardRoot = Environment.getExternalStorageDirectory(); 
                //create a new file, to save the downloaded file 
                File file = new File(SDCardRoot,"downloaded_file.png");
        
                FileOutputStream fileOutput = new FileOutputStream(file);
        
                //Stream used for reading the data from the internet
                InputStream inputStream = urlConnection.getInputStream();
        
                //this is the total size of the file which we are downloading
                totalSize = urlConnection.getContentLength();
        
                runOnUiThread(new Runnable() {
                    public void run() {
                        pb.setMax(totalSize);
                    }               
                });
        
                //create a buffer...
                byte[] buffer = new byte[1024];
                int bufferLength = 0;
        
                while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
                    fileOutput.write(buffer, 0, bufferLength);
                    downloadedSize += bufferLength;
                    // update the progressbar //
                    runOnUiThread(new Runnable() {
                        public void run() {
                            pb.setProgress(downloadedSize);
                            float per = ((float)downloadedSize/totalSize) *     
                            100;
                            cur_val.setText("Downloaded " + downloadedSize +  
        
                            "KB / " + totalSize + "KB (" + (int)per + "%)" );
                        }
                    });
                }
                //close the output stream when complete //
                fileOutput.close();
                runOnUiThread(new Runnable() {
                    public void run() {
                        // pb.dismiss(); // if you want close it..
                    }
                });         
        
            } catch (final MalformedURLException e) {
                showError("Error : MalformedURLException " + e);        
                e.printStackTrace();
            } catch (final IOException e) {
                showError("Error : IOException " + e);          
                e.printStackTrace();
            }
            catch (final Exception e) {
                showError("Error : Please check your internet connection " +  
        e);
            }       
        }
        
        void showError(final String err){
            runOnUiThread(new Runnable() {
                public void run() {
                    Toast.makeText(DownloadFileDemo1.this, err,  
              Toast.LENGTH_LONG).show();
                }
            });
        }
        
        void showProgress(String file_path){
            dialog = new Dialog(DownloadFileDemo1.this);
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setContentView(R.layout.myprogressdialog);
            dialog.setTitle("Download Progress");
        
            TextView text = (TextView) dialog.findViewById(R.id.tv1);
            text.setText("Downloading file from ... " + file_path);
            cur_val = (TextView) dialog.findViewById(R.id.cur_pg_tv);
            cur_val.setText("Starting download...");
            dialog.show();
        
             pb = (ProgressBar)dialog.findViewById(R.id.progress_bar);
             pb.setProgress(0);
                    pb.setProgressDrawable(
              getResources().getDrawable(R.drawable.green_progress));  
          }
        }
        

        【讨论】:

          【解决方案13】:

          我正在为我现在使用的其他解决方案添加另一个答案,因为 Android Query 太大且未维护以保持健康。所以我搬到了这个https://github.com/amitshekhariitbhu/Fast-Android-Networking

              AndroidNetworking.download(url,dirPath,fileName).build()
                .setDownloadProgressListener(new DownloadProgressListener() {
                  public void onProgress(long bytesDownloaded, long totalBytes) {
                      bar.setMax((int) totalBytes);
                      bar.setProgress((int) bytesDownloaded);
                  }
              }).startDownload(new DownloadListener() {
                  public void onDownloadComplete() {
                      ...
                  }
          
                  public void onError(ANError error) {
                      ...
                  }
              });
          

          【讨论】:

          • 使用此库下载较大的文件失败。 github.com/amitshekhariitbhu/Fast-Android-Networking/issues/541
          • @SathishGadde 好吧,你应该更多地调试它,因为这看起来不像是“库”问题......这个库是在 OkHttp 网络层之上制作的。因此,如果有一些下载问题,okhttp 也必须有,但我不认为是这种情况......您的问题可能有多种原因,很可能是网络问题。
          • 感谢您的快速响应。虽然我正在尝试使用小视频文件,但它工作正常。仅当文件大小较大(如 78mb)时才会出现问题。在上午 50mb 之后观察这个问题。
          • 好吧,也许会更好地提出单独的问题。正如我所说,FAN 不太可能是一个原因,因为它只是 ok http 库之上的 fin 网络层,但是您可以通过尝试使用纯 ok http 来自己找出。
          【解决方案14】:

          您可以使用 LiveData 和协程观察下载管理器的进度,请参阅下面的要点

          https://gist.github.com/FhdAlotaibi/678eb1f4fa94475daf74ac491874fc0e

          data class DownloadItem(val bytesDownloadedSoFar: Long = -1, val totalSizeBytes: Long = -1, val status: Int)
          
          class DownloadProgressLiveData(private val application: Application, private val requestId: Long) : LiveData<DownloadItem>(), CoroutineScope {
          
              private val downloadManager by lazy {
                  application.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
              }
          
              private val job = Job()
          
              override val coroutineContext: CoroutineContext
                  get() = Dispatchers.IO + job
          
              override fun onActive() {
                  super.onActive()
                  launch {
                      while (isActive) {
                          val query = DownloadManager.Query().setFilterById(requestId)
                          val cursor = downloadManager.query(query)
                          if (cursor.moveToFirst()) {
                              val status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS))
                              Timber.d("Status $status")
                              when (status) {
                                  DownloadManager.STATUS_SUCCESSFUL,
                                  DownloadManager.STATUS_PENDING,
                                  DownloadManager.STATUS_FAILED,
                                  DownloadManager.STATUS_PAUSED -> postValue(DownloadItem(status = status))
                                  else -> {
                                      val bytesDownloadedSoFar = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR))
                                      val totalSizeBytes = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES))
                                      postValue(DownloadItem(bytesDownloadedSoFar.toLong(), totalSizeBytes.toLong(), status))
                                  }
                              }
                              if (status == DownloadManager.STATUS_SUCCESSFUL || status == DownloadManager.STATUS_FAILED)
                                  cancel()
                          } else {
                              postValue(DownloadItem(status = DownloadManager.STATUS_FAILED))
                              cancel()
                          }
                          cursor.close()
                          delay(300)
                      }
                  }
              }
          
              override fun onInactive() {
                  super.onInactive()
                  job.cancel()
              }
          
          }
          

          【讨论】:

          • 你能提供这个类的用例示例吗?
          【解决方案15】:

          重要

          AsyncTask 在 Android 11 中已弃用。

          更多信息请查看以下帖子

          可能应该按照 google 的建议迁移到 concorency Framework

          【讨论】:

            【解决方案16】:
                private class DownloadTask extends AsyncTask<String, Integer, String> {
            
                    private PowerManager.WakeLock mWakeLock;
                    String onlinePathBundle, onlinePathMusic, offlinePathBundle, offlinePathMusic;
            
                    CircleProgressBar progressBar;
                    RelativeLayout rl_progress;
                    ImageView btn_download;
                    TextView tv_progress;
            
                    public DownloadTask(String onlinePathBundle, String onlinePathMusic, String offlinePathBundle, String offlinePathMusic, CircleProgressBar progressBar, RelativeLayout rl_progress, ImageView btn_download,
                                        TextView tv_progress) {
                        this.offlinePathBundle = offlinePathBundle;
                        this.offlinePathMusic = offlinePathMusic;
                        this.progressBar = progressBar;
                        this.rl_progress = rl_progress;
                        this.btn_download = btn_download;
                        this.tv_progress = tv_progress;
                        this.onlinePathBundle = onlinePathBundle;
                        this.onlinePathMusic = onlinePathMusic;
                    }
            
                    @Override
                    protected void onPreExecute() {
                        super.onPreExecute();
                        progressBar.setMax(100);
                        rl_progress.setVisibility(View.VISIBLE);
                        btn_download.setVisibility(View.GONE);
            
                        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
                        mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getName());
                        mWakeLock.acquire();
                    }
            
                    @Override
                    protected String doInBackground(String... sUrl) {
                        String firstResult = downTask(onlinePathBundle, 1, offlinePathBundle);
                        String seondResult = downTask(onlinePathMusic, 2, offlinePathMusic);
                        if (firstResult != null) {
                            Toast.makeText(SplashActivity.this, "Download error: " + firstResult, Toast.LENGTH_LONG).show();
                            return firstResult;
                        } else {
                            return seondResult;
                        }
            
                    }
            
                    @Override
                    protected void onProgressUpdate(Integer... progress) {
                        super.onProgressUpdate(progress);
                        progressBar.setProgress(progress[0]);
                        tv_progress.setText(progress[0] + "%");
            
                    }
            
                    @Override
                    protected void onPostExecute(String result) {
                        super.onPostExecute(result);
                        rl_progress.setVisibility(View.GONE);
                        btn_download.setVisibility(View.VISIBLE);
                        if (result != null) {
                            Toast.makeText(SplashActivity.this, "Download error: " + result, Toast.LENGTH_LONG).show();
                        } else {
                            rl_progress.setVisibility(View.GONE);
                            btn_download.setVisibility(View.GONE);
                        }
            
                    }
            
                    public String downTask(String onlineNewPath, int numberOfTask, String offlineNewPath) {
                        InputStream input = null;
                        OutputStream output = null;
                        HttpURLConnection connection = null;
                        try {
                            URL url = new URL(onlineNewPath);
                            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(offlineNewPath);
            
                            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
                                    if (numberOfTask == 1) {
                                        publishProgress((int) (total * 50 / fileLength));
                                    } else if (numberOfTask == 2) {
                                        publishProgress(((int) (total * 50 / fileLength)) + 50);
                                    }
            
                                }
                                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;
                    }
                }
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2013-09-18
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多