源码简介
实现自动更新,手机无SD卡也可以,本人亲测。
源码截图
源码片段
- int down_step = down_step_custom;// 提示step
- int totalSize;// 文件总大小
- int downloadCount = 0;// 已经下载好的大小
- int updateCount = 0;// 已经上传的文件大小
- InputStream inputStream;
- OutputStream outputStream;
- URL url = new URL(down_url);
- HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
- httpURLConnection.setConnectTimeout(TIMEOUT);
- httpURLConnection.setReadTimeout(TIMEOUT);
- // 获取下载文件的size
- totalSize = httpURLConnection.getContentLength();
- if (httpURLConnection.getResponseCode() == 404) {
- throw new Exception("fail!");
- //这个地方应该加一个下载失败的处理,但是,因为我们在外面加了一个try---catch,已经处理了Exception,
- //所以不用处理
- }
- inputStream = httpURLConnection.getInputStream();
- outputStream = new FileOutputStream(file, false);// 文件存在则覆盖掉
- byte buffer[] = new byte[1024];
- int readsize = 0;
- while ((readsize = inputStream.read(buffer)) != -1) {
- // /*********如果下载过程中出现错误,就弹出错误提示,并且把notificationManager取消*********/
- // if (httpURLConnection.getResponseCode() == 404) {
- // notificationManager.cancel(R.layout.notification_item);
- // throw new Exception("fail!");
- // //这个地方应该加一个下载失败的处理,但是,因为我们在外面加了一个try---catch,已经处理了Exception,
- // //所以不用处理
- // }
- outputStream.write(buffer, 0, readsize);
- downloadCount += readsize;// 时时获取下载到的大小
- /*** 每次增张3%**/
- if (updateCount == 0 || (downloadCount * 100 / totalSize - down_step) >= updateCount) {
- updateCount += down_step;
- // 改变通知栏
- contentView.setTextViewText(R.id.notificationPercent,updateCount + "%");
- contentView.setProgressBar(R.id.notificationProgress, 100,updateCount, false);
- notification.contentView = contentView;
- notificationManager.notify(R.layout.notification_item, notification);
- }
- }
- if (httpURLConnection != null) {
- httpURLConnection.disconnect();
- }
- inputStream.close();
- outputStream.close();
- return downloadCount;
源码链接:http://down.51cto.com/data/2012784