欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android开发中实现下载文件通知栏显示进度条

程序员文章站 2022-03-30 17:56:16
android开发中实现下载文件通知栏显示进度条。 1、使用asynctask异步任务实现,调用publishprogress()方法刷新进度来实现(已优化) public...

android开发中实现下载文件通知栏显示进度条。

1、使用asynctask异步任务实现,调用publishprogress()方法刷新进度来实现(已优化)

public class myasynctask extends asynctask {

    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);