Android 下载文件通知栏显示进度条功能的实例代码
作者:一个达布妞 发布时间:2023-09-01 19:42:50
标签:android,通知栏,进度条
1、使用AsyncTask异步任务实现,调用publishProgress()方法刷新进度来实现(已优化)
public class MyAsyncTask extends AsyncTask<String,Integer,Integer> {
private Context context;
private NotificationManager notificationManager;
private NotificationCompat.Builder builder;
public MyAsyncTask(Context context){
this.context = context;
notificationManager = (NotificationManager) context.getSystemService(Activity.NOTIFICATION_SERVICE);
builder = new NotificationCompat.Builder(context);
}
@Override
protected void onPreExecute() {
super.onPreExecute();
builder.setSmallIcon(R.mipmap.ic_launcher)
.setContentInfo("下载中...")
.setContentTitle("正在下载");
}
@Override
protected Integer doInBackground(String... params) {
Log.e(TAG, "doInBackground: "+params[0] );
InputStream is = null;
OutputStream os = null;
HttpURLConnection connection = null;
int total_length = 0;
try {
URL url1 = new URL(params[0]);
connection = (HttpURLConnection) url1.openConnection();
connection.setRequestMethod("GET");
connection.setReadTimeout(50000);
connection.connect();
if(connection.getResponseCode() == 200){
is = connection.getInputStream();
os = new FileOutputStream("/sdcard/zongzhi.apk");
byte [] buf = new byte[1024];
int len;
int pro1=0;
int pro2=0;
// 获取文件流大小,用于更新进度
long file_length = connection.getContentLength();
while((len = is.read(buf))!=-1){
total_length += len;
if(file_length>0) {
pro1 = (int) ((total_length / (float) file_length) * 100);//传递进度(注意顺序)
}
if(pro1!=pro2) {
// 调用update函数,更新进度
publishProgress(pro2=pro1);
}
os.write(buf, 0, len);
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
if (connection != null) {
connection.disconnect();
}
}
return total_length;
}
@Override
protected void onCancelled(Integer integer) {
super.onCancelled(integer);
}
@Override
protected void onCancelled() {
super.onCancelled();
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
builder.setProgress(100,values[0],false);
notificationManager.notify(0x3,builder.build());
//下载进度提示
builder.setContentText("下载"+values[0]+"%");
if(values[0]==100) { //下载完成后点击安装
Intent it = new Intent(Intent.ACTION_VIEW);
it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
it.setDataAndType(Uri.parse("file:///sdcard/zongzhi.apk"), "application/vnd.android.package-archive");
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, it, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentTitle("下载完成")
.setContentText("点击安装")
.setContentInfo("下载完成")
.setContentIntent(pendingIntent);
notificationManager.notify(0x3, builder.build());
}
}
@Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
if(integer == 100) {
Toast.makeText(context, "下载完成", Toast.LENGTH_SHORT).show();
}
}
}
2、使用系统服务来实现(不是特别推荐此方法)
//取得系统的下载服务
DownloadManager downloadManager= (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
//创建下载请求对象
DownloadManager.Request request=new DownloadManager.Request(Uri.parse(downUrl));
request.setDestinationInExternalPublicDir("目录","文件名");
request.setNotificationVisibility(DownloadManager.Request.NETWORK_MOBILE|DownloadManager.Request.NETWORK_WIFI);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
downloadManager.enqueue(request);
总结
以上所述是小编给大家介绍的Android 下载文件通知栏显示进度条功能的实例代码,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!
来源:https://blog.csdn.net/Fantistic_baby/article/details/78395691


猜你喜欢
- 本文实例为大家分享了QT实现简单计算器功能的具体代码,供大家参考,具体内容如下效果图:新建工程,创建类MainWindow,基类是QMain
- 最近在做项目的时候,一直用一个叫做API的东西,controller注解我会写,这个东西我也会用,但是我确实不知道这个东西是个什么,有点神奇
- 在处理网络请求时,有一部分功能是需要抽出来统一处理的,与业务隔开。登录校验可以利用spring mvc的 * Interceptor,实现H
- 在派生类中引发基类事件以下简单示例演示了在基类中声明可从派生类引发的事件的标准方法。此模式广泛应用于 .NET Framework 类库中的
- using System;using System.Collections.Generic;public class Example{ &n
- Unity3D UGUI Text得分数字增加 代码一、首先在Hierarchy中创建Text,并绑定脚本。using UnityEngin
- /// <summary>/// 获取数据缓存/// </summary>/// <param name=&q
- java分别解析下面两个json字符串package jansonDemo;import com.alibaba.fastjson.JSON
- 约瑟夫环是一个数学的应用问题:已知n个人(以编号1,2,3...n分别表示)围坐在一张圆桌周围。从编号为k的人开始报数,数到m的那个人出列;
- Lucene从今天开始,我们要开始介绍Lucene中索引构建的流程。因为索引构建的逻辑涉及到的东西非常多,如果从构建入口IndexWrite
- 在使用之前先介绍一个并发需要用到的方法:CountDownLatchCountDownLatch(也叫闭锁)是一个同步协助类,允许一个或多个
- @Async注解如何实现方法异步处理大批量数据的时候,效率很慢。所以考虑一下使用多线程。刚开始自己手写的一套,用了线程池启动固定的线程数进行
- java.util.NoSuchElementException报错的行数是一个scnner的next,本来和老师讨论了半天没有什么头绪,错
- 在 Flutter 中使用图片是最基础能力之一。作为春节开工后的第一篇文章,17 做了精心准备,满满的都是干货!本文介绍如何在 Flutte
- 前言最近项目做用户登录模块需要一个右边带图片的EditText,图片可以设置点击效果,所以就查资料做了一个自定义EditText出来,方便以
- 一、简介在开发程序的过程中,难免少不了写入错误日志这个关键功能。实现这个功能,可以选择使用第三方日志插件,也可以选择使用数据库,还可以自己写
- 主线程和子线程的区别每个线程都有一个唯一标示符,来区分线程中的主次关系的说法。 线程唯一标示符:Thread.CurrentThread.M
- /// <summary> /// 字符串转16进制字节数组 /// </summary> /// <para
- 前言实现轨迹回放,GMap.NET有对应的类GMapRoute。这个类函数很少,功能有限,只能实现简单的轨迹回放。要实现更复杂的轨迹回放,就
- 基本用法不说了,网上例子很多,这里主要介绍下比较特殊情况下使用的方法。1. 分组有的时候,我们对一个实体类需要有多中验证方式,在不同的情况下