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);
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值