Android实现简单的文件下载与上传
文件下载
/** *下载服务IntentService *生命周期: *1>当第一次启动IntentService时,Android容器 *将会创建IntentService对象。 *2>IntentService将会在工作线程中轮循消息队列, *执行每个消息对象中的业务逻辑。 *3>如果消息队列中依然有消息,则继续执行, *如果消息队列中的消息已经执行完毕, *IntentService将会自动销毁,执行onDestroy方法。 */ publicclassDownloadServiceextendsIntentService{ privatestaticfinalintNOTIFICATION_ID=100; publicDownloadService(){ super("download"); } publicDownloadService(Stringname){ super(name); } /** *该方法中的代码将会在工作线程中执行 *每当调用startService启动IntentService后, *IntentService将会把OnHandlerIntent中的 *业务逻辑放入消息队列等待执行。 *当工作线程轮循到该消息对象时,将会 *执行该方法。 */ protectedvoidonHandleIntent(Intentintent){ //发送Http请求执行下载业务 //1.获取音乐的路径 Stringurl=intent.getStringExtra("url"); Stringbit=intent.getStringExtra("bit"); Stringtitle=intent.getStringExtra("title"); //2.构建File对象,用于保存音乐文件 ///mnt/sdcard/Music/_64/歌名.mp3 FiletargetFile=newFile(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC),"_"+bit+"/"+title+".mp3"); if(targetFile.exists()){ Log.i("info","音乐已存在"); return; } if(!targetFile.getParentFile().exists()){ targetFile.getParentFile().mkdirs(); } try{ sendNotification("音乐开始下载","音乐开始下载"); //3.发送Http请求,获取InputStream InputStreamis=HttpUtils.getInputStream(url); //4.边读取边保存到File对象中 FileOutputStreamfos=newFileOutputStream(targetFile); byte[]buffer=newbyte[1024*100]; intlength=0; intcurrent=0; inttotal=Integer.parseInt(intent.getStringExtra("total")); while((length=is.read(buffer))!=-1){ fos.write(buffer,0,length); fos.flush(); current+=length; //通知下载的进度 doubleprogress=Math.floor(1000.0*current/total)/10; sendNotification("音乐开始下载","下载进度:"+progress+"%"); } //5.文件下载完成 fos.close(); cancelNotification();//重新出现滚动消息 sendNotification("音乐下载完成","音乐下载完毕"); }catch(Exceptione){ e.printStackTrace(); } } /** *发通知 */ publicvoidsendNotification(Stringticker,Stringtext){ NotificationManagermanager=(NotificationManager)getSystemService(NOTIFICATION_SERVICE); Notification.Builderbuilder=newNotification.Builder(this); builder.setSmallIcon(R.drawable.ic_launcher) .setContentTitle("音乐下载") .setContentText(text) .setTicker(ticker); Notificationn=builder.build(); manager.notify(NOTIFICATION_ID,n); } /** *取消通知 */ publicvoidcancelNotification(){ NotificationManagermanager=(NotificationManager)getSystemService(NOTIFICATION_SERVICE); manager.cancel(NOTIFICATION_ID); } }
文件上传
/** *上传文件 *@paramuploadFile */ privatevoiduploadFile(finalFileuploadFile){ newThread(newRunnable(){ @Override publicvoidrun(){ try{ uploadbar.setMax((int)uploadFile.length()); Stringsouceid=logService.getBindId(uploadFile); Stringhead="Content-Length="+uploadFile.length()+";filename="+uploadFile.getName()+";sourceid="+ (souceid==null?"":souceid)+"\r\n"; Socketsocket=newSocket("192.168.1.78",7878); OutputStreamoutStream=socket.getOutputStream(); outStream.write(head.getBytes()); PushbackInputStreaminStream=newPushbackInputStream(socket.getInputStream()); Stringresponse=StreamTool.readLine(inStream); String[]items=response.split(";"); Stringresponseid=items[0].substring(items[0].indexOf("=")+1); Stringposition=items[1].substring(items[1].indexOf("=")+1); if(souceid==null){//代表原来没有上传过此文件,往数据库添加一条绑定记录 logService.save(responseid,uploadFile); } RandomAccessFilefileOutStream=newRandomAccessFile(uploadFile,"r"); fileOutStream.seek(Integer.valueOf(position)); byte[]buffer=newbyte[1024]; intlen=-1; intlength=Integer.valueOf(position); while(start&&(len=fileOutStream.read(buffer))!=-1){ outStream.write(buffer,0,len); length+=len; Messagemsg=newMessage(); msg.getData().putInt("size",length); handler.sendMessage(msg); } fileOutStream.close(); outStream.close(); inStream.close(); socket.close(); if(length==uploadFile.length())logService.delete(uploadFile); }catch(Exceptione){ e.printStackTrace(); } } }).start(); } }
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对毛票票的支持。如果你想了解更多相关内容请查看下面相关链接
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。