Android文件下载之进度检测

2024-08-30 16:08
文章标签 android 检测 下载 进度

本文主要是介绍Android文件下载之进度检测,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

近期因为项目的需要,研究了一下Android文件下载进度显示的功能实现,接下来就和大家一起分享学习一下,希望对广大初学者有帮助。先上效果图:

Android文件下载之进度检测

上方的蓝色进度条,会根据文件下载量的百分比进行加载,中部的文本控件用来现在文件下载的百分比,最下方的ImageView用来展示下载好的文件,项目的目的就是动态向用户展示文件的下载量。

下面看代码实现:首先是布局文件:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"tools:context="${relativePackage}.${activityClass}" ><ProgressBarandroid:id="@+id/progressBar"style="?android:attr/progressBarStyleHorizontal"android:layout_width="match_parent"android:layout_height="wrap_content"android:max="100" /><TextViewandroid:id="@+id/textView"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_below="@+id/progressBar"android:layout_centerHorizontal="true"android:layout_marginTop="24dp"android:text="TextView" /><ImageViewandroid:id="@+id/imageView"android:layout_marginTop="24dp"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_alignParentBottom="true"android:layout_below="@+id/textView"android:contentDescription="@string/app_name"android:src="@drawable/ic_launcher" /></RelativeLayout>

接下来的主Activity代码:

public class MainActivity extends Activity {ProgressBar pb;   TextView tv; ImageView imageView;int fileSize;    int downLoadFileSize;    String fileEx,fileNa,filename;  //用来接收线程发送来的文件下载量,进行UI界面的更新private Handler handler = new Handler(){    @Override    public void handleMessage(Message msg)    {//定义一个Handler,用于处理下载线程与UI间通讯if (!Thread.currentThread().isInterrupted()){    switch (msg.what){    case 0:    pb.setMax(fileSize);case 1:    pb.setProgress(downLoadFileSize);    int result = downLoadFileSize * 100 / fileSize;    tv.setText(result + "%");    break;    case 2:    Toast.makeText(MainActivity.this, "文件下载完成", Toast.LENGTH_SHORT).show();   FileInputStream fis = null;try {fis = new FileInputStream(Environment.getExternalStorageDirectory() + File.separator + "/ceshi/" + filename);} catch (FileNotFoundException e) {e.printStackTrace();}Bitmap bitmap = BitmapFactory.decodeStream(fis);  ///把流转化为Bitmap图imageView.setImageBitmap(bitmap);break;    case -1:    String error = msg.getData().getString("error");Toast.makeText(MainActivity.this, error, Toast.LENGTH_SHORT).show();    break;    }    }    super.handleMessage(msg);    }    };@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);pb=(ProgressBar)findViewById(R.id.progressBar);tv=(TextView)findViewById(R.id.textView);imageView = (ImageView) findViewById(R.id.imageView);tv.setText("0%");new Thread(){public void run(){try {//下载文件,参数:第一个URL,第二个存放路径down_file("http://cdnq.duitang.com/uploads/item/201406/15/20140615203435_ABQMa.jpeg", Environment.getExternalStorageDirectory() + File.separator + "/ceshi/");} catch (ClientProtocolException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}   }    }.start();    }    /*** 文件下载* @param url:文件的下载地址* @param path:文件保存到本地的地址* @throws IOException*/public void down_file(String url,String path) throws IOException{    //下载函数          filename=url.substring(url.lastIndexOf("/") + 1);//获取文件名    URL myURL = new URL(url);URLConnection conn = myURL.openConnection();    conn.connect();    InputStream is = conn.getInputStream();    this.fileSize = conn.getContentLength();//根据响应获取文件大小    if (this.fileSize <= 0) throw new RuntimeException("无法获知文件大小 ");    if (is == null) throw new RuntimeException("stream is null"); File file1 = new File(path);File file2 = new File(path+filename);if(!file1.exists()){file1.mkdirs();}if(!file2.exists()){file2.createNewFile();}FileOutputStream fos = new FileOutputStream(path+filename);    //把数据存入路径+文件名    byte buf[] = new byte[1024];downLoadFileSize = 0;    sendMsg(0);    do{    //循环读取    int numread = is.read(buf);    if (numread == -1)    {    break;    }    fos.write(buf, 0, numread);    downLoadFileSize += numread;    sendMsg(1);//更新进度条    } while (true);  sendMsg(2);//通知下载完成    try{    is.close();    } catch (Exception ex) {    Log.e("tag", "error: " + ex.getMessage(), ex);    }    }    //在线程中向Handler发送文件的下载量,进行UI界面的更新private void sendMsg(int flag)    {    Message msg = new Message();    msg.what = flag;    handler.sendMessage(msg);    }        }

最后一定要注意的是:在AndroidManifest.xml文件中,添加访问网络的权限

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

到这里关于Android文件下载动态显示下载进度的小demo就为大家分享完毕,希望对大家的学习有所帮助。


转自:http://www.codeceo.com/article/android-file-prograssbar.html

这篇关于Android文件下载之进度检测的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1121290

相关文章

Android协程高级用法大全

《Android协程高级用法大全》这篇文章给大家介绍Android协程高级用法大全,本文结合实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友跟随小编一起学习吧... 目录1️⃣ 协程作用域(CoroutineScope)与生命周期绑定Activity/Fragment 中手

Python多线程实现大文件快速下载的代码实现

《Python多线程实现大文件快速下载的代码实现》在互联网时代,文件下载是日常操作之一,尤其是大文件,然而,网络条件不稳定或带宽有限时,下载速度会变得很慢,本文将介绍如何使用Python实现多线程下载... 目录引言一、多线程下载原理二、python实现多线程下载代码说明:三、实战案例四、注意事项五、总结引

Python脚本轻松实现检测麦克风功能

《Python脚本轻松实现检测麦克风功能》在进行音频处理或开发需要使用麦克风的应用程序时,确保麦克风功能正常是非常重要的,本文将介绍一个简单的Python脚本,能够帮助我们检测本地麦克风的功能,需要的... 目录轻松检测麦克风功能脚本介绍一、python环境准备二、代码解析三、使用方法四、知识扩展轻松检测麦

Android 缓存日志Logcat导出与分析最佳实践

《Android缓存日志Logcat导出与分析最佳实践》本文全面介绍AndroidLogcat缓存日志的导出与分析方法,涵盖按进程、缓冲区类型及日志级别过滤,自动化工具使用,常见问题解决方案和最佳实... 目录android 缓存日志(Logcat)导出与分析全攻略为什么要导出缓存日志?按需过滤导出1. 按

Android Paging 分页加载库使用实践

《AndroidPaging分页加载库使用实践》AndroidPaging库是Jetpack组件的一部分,它提供了一套完整的解决方案来处理大型数据集的分页加载,本文将深入探讨Paging库... 目录前言一、Paging 库概述二、Paging 3 核心组件1. PagingSource2. Pager3.

SQL server数据库如何下载和安装

《SQLserver数据库如何下载和安装》本文指导如何下载安装SQLServer2022评估版及SSMS工具,涵盖安装配置、连接字符串设置、C#连接数据库方法和安全注意事项,如混合验证、参数化查... 目录第一步:打开官网下载对应文件第二步:程序安装配置第三部:安装工具SQL Server Manageme

Linux系统性能检测命令详解

《Linux系统性能检测命令详解》本文介绍了Linux系统常用的监控命令(如top、vmstat、iostat、htop等)及其参数功能,涵盖进程状态、内存使用、磁盘I/O、系统负载等多维度资源监控,... 目录toppsuptimevmstatIOStatiotopslabtophtopdstatnmon

Android kotlin中 Channel 和 Flow 的区别和选择使用场景分析

《Androidkotlin中Channel和Flow的区别和选择使用场景分析》Kotlin协程中,Flow是冷数据流,按需触发,适合响应式数据处理;Channel是热数据流,持续发送,支持... 目录一、基本概念界定FlowChannel二、核心特性对比数据生产触发条件生产与消费的关系背压处理机制生命周期

Android ClassLoader加载机制详解

《AndroidClassLoader加载机制详解》Android的ClassLoader负责加载.dex文件,基于双亲委派模型,支持热修复和插件化,需注意类冲突、内存泄漏和兼容性问题,本文给大家介... 目录一、ClassLoader概述1.1 类加载的基本概念1.2 android与Java Class

使用Python实现可恢复式多线程下载器

《使用Python实现可恢复式多线程下载器》在数字时代,大文件下载已成为日常操作,本文将手把手教你用Python打造专业级下载器,实现断点续传,多线程加速,速度限制等功能,感兴趣的小伙伴可以了解下... 目录一、智能续传:从崩溃边缘抢救进度二、多线程加速:榨干网络带宽三、速度控制:做网络的好邻居四、终端交互