首页 > Java > 使用 Android 下载文件,并在 ProgressDialog 中显示进度

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

上一篇 下一篇

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

分割线

网友回答:

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

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

分割线

网友回答:

有很多方法可以下载文件。接下来我将发布最常见的方法;由你决定哪种方法更适合你的应用。

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

上面的方法()始终在后台线程上运行。你不应该在那里执行任何 UI 任务。另一方面,和在UI线程上运行,因此您可以在此处更改进度条:doInBackgroundonProgressUpdateonPreExecute

    @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" />
  1. 从服务下载
    ========================

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

下载服务可能如下所示:

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是一个库,基本上可以帮助你在后台服务中运行代码片段,它基于上面显示的概念。此库目前已弃用整个代码如下所示: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"/>

我认为这再简单不过了。只需从Github上拿起最新的罐子,您就可以开始了。请记住,Groundy的主要目的是在后台服务中调用外部REST API,并轻松地将结果发布到UI。如果您在应用程序中执行类似操作,它可能非常有用。

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

  1. 使用类(仅限更新版本)DownloadManagerGingerBread
    =============================================================

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_STORAGEACCESS_NETWORK_STATE
  • 确保您要下载文件的目录存在并具有写入权限。
  • 如果下载太大,您可能需要实现一种方法,以便在以前的尝试失败时恢复下载。
  • 如果您允许用户中断下载,他们将不胜感激。

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

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

此类在 API 级别 26 中已弃用。进度对话框是一个模式
对话框,可阻止用户与应用交互。不应使用此类,而
应使用进度条等
进度指示器,该指示器可以嵌入到应用的 UI 中。或者,
您可以使用通知通知用户任务的进度。更多详情链接

分割线

网友回答:

是的,上面的代码将起作用.但是,如果您要更新您的 in 并按下后退按钮或完成您的活动,则会失去您的 UI 跟踪。当您返回活动时,即使下载在后台运行,您也不会在进度条上看到任何更新。因此,尝试运行一个线程,就像使用计时器任务一样,该任务使用从运行后台更新的值来更新您的值。progressbaronProgressUpdateAsynctaskAsyncTaskOnResume()runOnUIThreadprogressbarAsyncTask

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

模板简介:该模板名称为【使用 Android 下载文件,并在 ProgressDialog 中显示进度】,大小是暂无信息,文档格式为.编程语言,推荐使用Sublime/Dreamweaver/HBuilder打开,作品中的图片,文字等数据均可修改,图片请在作品中选中图片替换即可,文字修改直接点击文字修改即可,您也可以新增或修改作品中的内容,该模板来自用户分享,如有侵权行为请联系网站客服处理。欢迎来懒人模板【Java】栏目查找您需要的精美模板。

相关搜索
  • 下载密码 lanrenmb
  • 下载次数 392次
  • 使用软件 Sublime/Dreamweaver/HBuilder
  • 文件格式 编程语言
  • 文件大小 暂无信息
  • 上传时间 02-25
  • 作者 网友投稿
  • 肖像权 人物画像及字体仅供参考
栏目分类 更多 >
热门推荐 更多 >
微信公众平台 微信素材 微信图片 微信模板 html5 企业网站 自适应 响应式 单页式简历模板 微信文章
您可能会喜欢的其他模板