介绍
这篇文章主要介绍了Android如何实现简单的文件下载与上传,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获、下面让小编带着大家一起了解一下。
<强>文件下载强>
/* * ,*下载服务,IntentService ,*生命周期: ,* 1在当第一次启动IntentService时,Android容器 ,*,将会创建IntentService对象。 ,* 2祝辞IntentService将会在工作线程中轮循消息队列, ,*,执行每个消息对象中的业务逻辑。 ,* 3的在如果消息队列中依然有消息,则继续执行, ,*,如果消息队列中的消息已经执行完毕, ,*,IntentService将会自动销毁,执行onDestroy方法。 ,*/public class  DownloadService extends  IntentService { private 才能static final  int NOTIFICATION_ID =, 100; public 才能;DownloadService () { ,,,超级(“download"); ,,} public 才能DownloadService (String 名称),{ ,,,超级(名称); ,,} ,/* * ,,*,该方法中的代码将会在工作线程中执行 ,,*,每当调用startService启动IntentService后, ,,*,IntentService将会把OnHandlerIntent中的 ,,*,业务逻辑放入消息队列等待执行。 ,,*,当工作线程轮循到该消息对象时,将会 ,,*,执行该方法。 ,,*/protected 才能;void  onHandleIntent (Intent 意图),{ ,,,//发送Http请求,执行下载业务 ,,,//1只获取音乐的路径 ,,,String url=intent.getStringExtra (“url"); ,,,String 一些=intent.getStringExtra (“bit"); ,,,String title=intent.getStringExtra (“title"); ,,,//2只构建文件对象,用于保存音乐文件 ,,,//,,,/mnt/sdcard/音乐/_64/歌名。mp3 ,,,File targetFile =, new 文件(Environment.getExternalStoragePublicDirectory (Environment.DIRECTORY_MUSIC),“_" +点+“/?名称+“.mp3",),,,,,,,,,, ,,,如果(targetFile.exists ()) { ,,,,,Log.i (“info",,“音乐已存在“); ,,,,,返回; ,,,} ,,,如果(! targetFile.getParentFile () .exists ()) { ,,,,,targetFile.getParentFile () .mkdirs (); ,,,} ,,,try { ,,,,,sendNotification(“音乐开始下载“,,“音乐开始下载“); ,,,,,//3只发送Http请求,获取InputStream ,,,,,InputStream is =, HttpUtils.getInputStream (url); ,,,,,//4只边读取边保存到文件对象中 ,,,,,FileOutputStream fos =, new FileOutputStream (targetFile); ,,,,,byte [], buffer =, new 字节(1024 * 100); ,,,,,int 长度=0; ,,,,,int current =, 0; ,,,,,int total =, Integer.parseInt (intent.getStringExtra (“total")); ,,,,,,((长度=is.read(缓冲)),!=,1){ ,,,,,,,fos.write(缓冲区,,0,,长度); ,,,,,,,fos.flush (); ,,,,,,,current +=,长度; ,,,,,,,//通知下载的进度 ,,,,,,,double progress =, Math.floor(1000.0 *当前/总)/10; ,,,,,,,sendNotification(“音乐开始下载“,,“下载进度:“+进步+“%”); ,,,,,} ,,,,,//5只文件下载完成 ,,,,,fos.close (); ,,,,,cancelNotification();,//重新出现滚动消息 ,,,,,sendNotification(“音乐下载完成,,,“音乐下载完毕“); ,,,},catch (Exception e), { ,,,,,e.printStackTrace (); ,,,} ,,} ,/* * ,,*,发通知 ,,*/public 才能;void  sendNotification (String 股票,String 文本){ ,,,NotificationManager manager =, (NotificationManager), getSystemService (NOTIFICATION_SERVICE); ,,,Notification.Builder builder =, new Notification.Builder(这个); ,,,builder.setSmallIcon (R.drawable.ic_launcher) ,,,,,.setContentTitle(“音乐下载“) ,,,,,.setContentText(文本) ,,,,,.setTicker(股票); ,,,Notification n =, builder.build (); null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null nullAndroid如何实现简单的文件下载与上传