一切从简
两个结合来讲解,使用服务和通知进行后台下载
一个页面,用于启动服务,上面只有一个Button,不列出布局文件了。
启动service
Intent integer=new Intent(Service_Main.this,Servier__.class); startService(integer);
Servier__类中:全局变量int Add_Lenth;下载进度(字节) int Sudu;下载速度(字节) int Lenth;文件大小(字节)int Index;下载的时间文件的下载 下载地址 文件名 本机保存的位置
public void Get_HttpUrl_File(String urlStr, String fileName, String savePath) throws IOException {
HttpURLConnection conn=(HttpURLConnection) new URL(urlStr).openConnection();
//打开连接 conn.setRequestMethod("GET");
//设置请求类型 conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//设置请求头属性 InputStream inputStream = conn.getInputStream();
//正式进行请求 byte[] bytes=new byte[1024];
//一个1024的数组,用于保存下载的文件流 int hasRea=0;
//用于临时保存文件流 Timer timer=new Timer();
timer.schedule(task,0,1000);
//开始下载便进行通知,1秒更新一次
//最大字节数Lenth =conn.getContentLength();
while((hasRea=inputStream.read(bytes))>0){RandomAccessFile currFile=new RandomAccessFile(savePath+fileName,"rw");
//文件保存区(非内存)直接对文件进行保存
//读取下载的文件流, currFile.write(bytes,0,hasRea);
//进行读写 Add_Lenth+=hasRea;
//下载进度(字节) Sudu+=hasRea;
//下载速度(字节),之所以有两个是因为速度回被清空 } currFile.close();
//关闭 inputStream.close();
}//关闭
//计时器
TimerTask task=new TimerTask() { @Override public void run() {//子线程更新 Index+=1;
//每秒加一 NotificationManager manger= (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//通知控制器
Notification noti = new Notification.Builder(getApplicationContext())//编写通知
.setAutoCancel(true)//单击消失 .setProgress(Lenth,Add_Lenth,false)//通知的进度条 .setContentTitle("下载中" )//标题 .setContentText(String.valueOf(Sudu/1024)+"K"+"----"+Index+"秒----------"+Add_Lenth+"/"+Lenth) .setSmallIcon(R.mipmap.ic_launcher)//图片 .build(); manger.notify(999, noti);//启用 Sudu=0;//重置时间 } };
onCreate函数!!记得开网络权限!!@Override public void onCreate() {//启动服务进行的函数 super.onCreate(); Index=0;
//初始化时间 new Thread(new Runnable() { @Override public void run() { final String path = Environment.getExternalStorageDirectory().getPath() + "/AAAAImg/";
//获取目录 try { Get_HttpUrl_File("http://sqdownb.onlinedown.net/down/TaoBao_630.apk","baidu.apk",path);
//调用网络函数(下载地址,下载后的保存名字,目录) } catch (IOException e) { e.printStackTrace(); } } }).start();
//启动 }
这里只做最初级的显示效果