Android 下载文件通知栏显示进度条功能的实例代码

 更新时间:2018年04月21日 14:21:46   作者:一个达布妞  
这篇文章主要介绍了Android 下载文件通知栏显示进度条功能的实例代码,通过使用AsyncTask异步任务实现,调用publishProgress()方法刷新进度来实现,具体代码大家参考下本文

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 下载文件通知栏显示进度条功能的实例代码,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!

相关文章

  • Android WorkManager实现后台定时任务流程详解

    Android WorkManager实现后台定时任务流程详解

    WorkManager是Android Jetpack的一个强大的组件,用于处理后台耗时任务。后台任务可以是一次性的,也可以是重复的,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习吧
    2023-01-01
  • 微信小程序—微信跳一跳,Android游戏助手(外挂)使用教程详解

    微信小程序—微信跳一跳,Android游戏助手(外挂)使用教程详解

    这篇文章主要介绍了微信小程序—微信跳一跳,Android游戏助手(外挂)使用教程详解,需要的朋友可以参考下
    2018-01-01
  • Android如何获取屏幕、状态栏及标题栏的高度详解

    Android如何获取屏幕、状态栏及标题栏的高度详解

    在日常开发中,经常会遇到获取屏幕高度、状态栏高度等需求,所以下面这篇文章就给大家总结介绍了关于Android如何获取屏幕、状态栏及标题栏高度的相关资料,文中通过示例代码介绍的非常详细,需要的朋友们可以参考下。
    2017-10-10
  • Kotlin协程Channel源码示例浅析

    Kotlin协程Channel源码示例浅析

    这篇文章主要为大家介绍了Kotlin协程Channel源码示例浅析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-12-12
  • 利用Android从0到1实现一个流布局控件

    利用Android从0到1实现一个流布局控件

    新项目用到了一种全新布局,Android标签流式布局的功能,正好一直说给大家讲自己定义控件的实现,这篇文章主要给大家介绍了关于利用Android从0到1如何实现一个流布局控件的相关资料,需要的朋友可以参考下
    2021-08-08
  • android 使用浏览器打开指定页面的实现方法

    android 使用浏览器打开指定页面的实现方法

    这篇文章主要介绍了android 使用浏览器打开指定页面的实现方法,本文通过实例文字说明的形式给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下
    2018-06-06
  • Android14原生PackageInstaller安装某些apk报错问题

    Android14原生PackageInstaller安装某些apk报错问题

    本文主要介绍了在Android 14上安装大型应用时遇到的java.lang.RuntimeException: Could not copy bitmap to parcel blob错误,下面就一起来介绍一下解决方法,感兴趣的可以了解一下
    2025-03-03
  • android基础教程之开机启动示例

    android基础教程之开机启动示例

    这篇文章主要介绍了android开机启动示例,开机自动启动程序后开机启动广播功能实现,需要的朋友可以参考下
    2014-02-02
  • Android自定义ImageView实现圆角功能

    Android自定义ImageView实现圆角功能

    这篇文章主要为大家详细介绍了Android自定义ImageView实现圆角功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-12-12
  • Android实现底部半透明弹出框PopUpWindow效果

    Android实现底部半透明弹出框PopUpWindow效果

    这篇文章主要为大家详细介绍了Android实现底部半透明弹出框PopUpWindow效果,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-07-07

最新评论