通过服务来下载APK,并在通知栏显示下载进度(两种方式)

private NotificationManager nm;
    private NotificationCompat.Builder builder;
    private Notification nf;

 @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("====", "服务启动--非绑定方式");
        if(intent!=null){
            Boolean flag=intent.getBooleanExtra("download", true);
            if(flag){
                String url="http://10.0.2.2:8080/HttpTest/weixin.apk";
                downLoad(url);//调用系统的下载服务
            }else{
                nm= (NotificationManager) getSystemService(Activity.NOTIFICATION_SERVICE);
                builder= new NotificationCompat.Builder(getBaseContext());
                String url="http://10.0.2.2:8080/HttpTest/weixin.apk";
                new MyDownloadAnsy().execute(url);//自定义notification
            }

        }
        return super.onStartCommand(intent, flags, startId);
    }

public void downLoad(String downUrl) {
        //取得系统的下载服务
        DownloadManager downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
        //创建下载请求对象
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(downUrl));
        request.setDestinationInExternalPublicDir("sdcard/Download/", "test.apk");
        request.setNotificationVisibility(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        downloadManager.enqueue(request);
    }


public class MyDownloadAnsy extends AsyncTask<String,Integer,Integer> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            RemoteViews contentView=new RemoteViews(getPackageName(),R.layout.notification_layout);
            contentView.setTextViewText(R.id.tv,"测试.apk");
            contentView.setProgressBar(R.id.pb,100,0,false);
            builder.setContent(contentView).setSmallIcon(R.mipmap.ic_launcher);
            nf=builder.build();
            nm.notify(0,nf);
        }

        @Override
        protected Integer doInBackground(String... params) {
            HttpURLConnection con=null;
            InputStream is=null;
            OutputStream os=null;
            try {
                URL url=new URL(params[0]);
                con= (HttpURLConnection) url.openConnection();
                con.setConnectTimeout(5*1000);  //设置超时时间
                if(con.getResponseCode()==200){ //判断是否连接成功
                    int fileLength = con.getContentLength();
                    is=con.getInputStream();    //获取输入
                    os = new FileOutputStream("/sdcard/weixin.apk");
                    byte[] buffer=new byte[1024*1024*10];
                    long total=0;
                    int count;
                    int pro1=0;
                    int pro2=0;
                    while ((count=is.read(buffer))!=-1){
                        total+=count;
                        if (fileLength > 0)
                            pro1=(int) (total * 100 / fileLength);  //传递进度(注意顺序)
                        if(pro1!=pro2)
                            publishProgress(pro2=pro1);
                        os.write(buffer,0,count);
                    }
                }
            } 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(con!=null){
                    con.disconnect();
                }
            }
            return 1;
        }

        @Override
        protected void onPostExecute(Integer result) {
            super.onPostExecute(result);

            if(result==1){
                Toast.makeText(MyService.this, "下载完成", Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            Log.d("===",""+values[0]);
            super.onProgressUpdate(values);
            RemoteViews contentView=nf.contentView;
            contentView.setProgressBar(R.id.pb,100,values[0],false);
            nm.notify(0,nf);
            if(values[0]==100) {    //下载完成后点击安装
                Intent it = new Intent(Intent.ACTION_VIEW);
                it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                it.setDataAndType(Uri.parse("file:///sdcard/weixin.apk"), "application/vnd.android.package-archive");
                PendingIntent pendingIntent = PendingIntent.getActivity(getBaseContext(), 0, it, PendingIntent.FLAG_UPDATE_CURRENT);
                contentView.setTextViewText(R.id.tv,"下载完成");
                builder.setContent(contentView).setContentIntent(pendingIntent);
                nf=builder.build();
                nm.notify(0,nf);
            }
        }
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值