android 下载进度条的实现

android 下载进度条的实现

最近在写关于多线程下执行多任务同时下载的问题,其实就是单线程下任务下载的升级,现在把单线程下下载的进度条整理一下:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
 
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
 
public class FileDownProcessBarActivity extends Activity {
    /** Called when the activity is first created. */
    private static final String Path="http://210.30.12.1:8080/mp3/DJ.mp3";
    private ProgressBar progressBar;
    private TextView textView;
    private Button button;
    private int FileLength;
    private int DownedFileLength=0;
    private InputStream inputStream;
    private URLConnection connection;
    private OutputStream outputStream;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        progressBar=(ProgressBar) findViewById(R.id.progressBar1);
        textView=(TextView) findViewById(R.id.textView2);
        button=(Button) findViewById(R.id.button1);
        button.setOnClickListener(new ButtonListener());
    }
    class ButtonListener implements OnClickListener{
 
        @Override
        public void onClick(View v) {
            DownedFileLength=0;
            // TODO Auto-generated method stub
           Thread thread=new Thread(){
             public void run(){
                 try {
                    DownFile(Path);
                } catch (Exception e) {
                    // TODO: handle exception
                }
             }
           };
           thread.start();
        }  
    }
    private Handler handler=new Handler()
    {
         public void handleMessage(Message msg)
        {
        if (!Thread.currentThread().isInterrupted()) {
            switch (msg.what) {
            case 0:
                progressBar.setMax(FileLength);
                Log.i("文件长度----------->", progressBar.getMax()+""); 
                break;
            case 1:
                progressBar.setProgress(DownedFileLength);
                int x=DownedFileLength*100/FileLength;
                textView.setText(x+"%");
                break;
            case 2:
                Toast.makeText(getApplicationContext(), "下载完成", Toast.LENGTH_LONG).show();
                break;
                 
            default:
                break;
            }
        }  
        }
          
    };
 
    private void DownFile(String urlString)
    {
         
        /*
         * 连接到服务器
         */
         
        try {
             URL url=new URL(urlString);
             connection=url.openConnection();
             if (connection.getReadTimeout()==5) {
                Log.i("---------->", "当前网络有问题");
                // return;
               }
             inputStream=connection.getInputStream();
             
        } catch (MalformedURLException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
         
        /*
         * 文件的保存路径和和文件名其中Nobody.mp3是在手机SD卡上要保存的路径,如果不存在则新建
         */
        String savePAth=Environment.getExternalStorageDirectory()+"/DownFile";
        File file1=new File(savePAth);
        if (!file1.exists()) {
            file1.mkdir();
        }
        String savePathString=Environment.getExternalStorageDirectory()+"/DownFile/"+"DJ.mp3";
        File file =new File(savePathString);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }  
        }
        /*
         * 向SD卡中写入文件,用Handle传递线程
         */
        Message message=new Message();
        try {
            outputStream=new FileOutputStream(file);
            byte [] buffer=new byte[1024*4];
            FileLength=connection.getContentLength();
            message.what=0;
            handler.sendMessage(message);
            while (DownedFileLength<FileLength) {
                outputStream.write(buffer);
                DownedFileLength+=inputStream.read(buffer);
                Log.i("-------->", DownedFileLength+"");
                Message message1=new Message();
                message1.what=1;
                handler.sendMessage(message1);
            }
            Message message2=new Message();
            message2.what=2;
            handler.sendMessage(message2);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
       
}

多任务同时下载的话,就用线程池的思想去做管理,把任务加到线程池去执行,去和服务绑定然后显示下载进度。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android 中显示下载进度条可以使用 ProgressDialog。首先需要创建一个 AsyncTask 类,然后在 doInBackground 方法中进行下载操作并更新进度条,最后在 onPostExecute 方法中完成下载。 以下是一个示例代码: ```java public class DownloadTask extends AsyncTask<String, Integer, String> { private Context context; private PowerManager.WakeLock mWakeLock; private ProgressDialog mProgressDialog; public DownloadTask(Context context) { this.context = context; } @Override protected void onPreExecute() { super.onPreExecute(); // 创建进度条对话框并设置样式 mProgressDialog = new ProgressDialog(context); mProgressDialog.setMessage("正在下载,请稍候..."); mProgressDialog.setIndeterminate(false); mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); mProgressDialog.setCancelable(true); mProgressDialog.show(); // 保持屏幕亮度 PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE); mWakeLock = powerManager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, getClass().getSimpleName()); mWakeLock.acquire(); } @Override protected String doInBackground(String... urls) { InputStream input = null; OutputStream output = null; HttpURLConnection connection = null; try { URL url = new URL(urls[0]); connection = (HttpURLConnection) url.openConnection(); connection.connect(); // 获取文件大小 int fileLength = connection.getContentLength(); // 创建输入流和输出流 input = connection.getInputStream(); output = new FileOutputStream(Environment.getExternalStorageDirectory().getPath() + "/downloadedfile.mp4"); byte data[] = new byte[4096]; long total = 0; int count; while ((count = input.read(data)) != -1) { total += count; // 更新进度条 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 onProgressUpdate(Integer... values) { super.onProgressUpdate(values); // 更新进度条 mProgressDialog.setProgress(values[0]); } @Override protected void onPostExecute(String result) { super.onPostExecute(result); // 关闭进度条对话框 mProgressDialog.dismiss(); mWakeLock.release(); if (result != null) Toast.makeText(context, "下载出错:" + result, Toast.LENGTH_LONG).show(); else Toast.makeText(context, "下载完成", Toast.LENGTH_SHORT).show(); } } ``` 使用时,只需要创建一个 DownloadTask 对象并调用 execute 方法即可: ```java new DownloadTask(this).execute("http://example.com/file.mp4"); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值