Android从服务器下载文件
2016-01-29 13:26
387 查看
//下载文件到sdcard,并自动进入软件安装界面 private void downloadNewAPP() { new Thread(){ public void run() { InputStream in = null; FileOutputStream out = null; try { //创建httpclient HttpClient client = new DefaultHttpClient(); //设置超时时长 client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 3000); //请求方式 HttpGet request = new HttpGet(path); //执行请求 HttpResponse response = client.execute(request); //判断响应码 if (response.getStatusLine().getStatusCode() == 200) { //获取apk流对象 in = response.getEntity().getContent(); //创建输出流 File file = new File(Environment.getExternalStorageDirectory(),getFileName(path)); out = new FileOutputStream(file); //下载 byte[] buffer = new byte[1024]; int len = 0; while((len = in.read(buffer))!=-1){ out.write(buffer, 0, len); } //弹出安装界面 //创建message对象 Message msg = Message.obtain(); //设置类型 msg.what = INSTALL_NEW_VERSION; //发送消息 handler.sendMessage(msg); } } catch (Exception e) { e.printStackTrace(); } finally { //释放流 try { if (out != null) { out.close(); } } catch (IOException e) { e.printStackTrace(); } try { if (in != null) { in.close(); } } catch (IOException e) { e.printStackTrace(); } } }; }.start(); } //获取文件名 private String getFileName(String path) { return path.substring(path.lastIndexOf("/")); }
相关文章推荐
- android mvp快速开发框架介绍(自动生成android代码工具介绍)
- 拥抱 Android Studio 之四:Maven 仓库使用与私有仓库搭建
- Android开发,如何使canvas画布背景色透明。
- 阅读《Android 从入门到精通》(19)——评分条
- android-Implementing Effective Navigation,Creating Swipe Views with Tabs
- Android之使用 Intent 传递对象(一)Parcelable 方式
- Android 开源项目分类汇总--1
- Android之使用 Intent 传递对象(一)Serializable 方式
- Android之全局获取 Context 的技巧
- Android之传感器(三)方向传感器
- 编译使用opencv库的android程序
- android 常用action和category
- Android布局优化之Merge Include ViewStub使用与源码分析
- 移植opencv2.4.9到android过程记录
- Android游戏——2048的设计
- Android中的动画具体解释系列【4】——Activity之间切换动画
- PopupWindow在android6.0无法弹出问题
- Android版俄罗斯方块
- android中保存Bitmap图片到指定文件夹中的方法
- 【整理】Android中EditText中的InputType类型含义与如何定义