android 下载的时候在ProgressDialog同时显示进度条

文章标签:
2014-10-26 12:50:19     人阅读    

     我想编写一个可以自动更新的android app,功能需要app一边下载需要更新的文件,一边通过ProgressDialog 显示下载的进度,我会使用ProgressDialog,但是不会如何与下载服务交流,展示正确的进度。

 

处理方法

android下载的方式多种多样
1. 使用 AsyncTask 下载和采用dialog展示下载进度
AsyncTask 方法运行你在后台跑任务,在跑的同时更新前台ui进程

代码如下::

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


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 {



    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界面,
onProgressUpdate and onPreExecute 是在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();
 
    }


For this to run, you need the WAKE_LOCK permission.


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


原文地址:http://www.itmmd.com/201410/63.html
该文章由 萌萌的IT人 整理发布,转载须标明出处。

选装android手机,Activity 重新启动的问题   上一篇
下一篇  Android 报错 Activity 状态
精彩回复
我要追加问题,请求站长解决!
姓名:       

《程序员app》专门为程序员量身定做!