- 浏览: 61274 次
- 性别:
- 来自: 上海
文章分类
最新评论
-
u014549257:
...
Apache Mina: StreamIoHandler传输文件处理 -
至尊包:
想问一下,这个官网的列子如果要兼容3.0以下的版本要怎么处理? ...
Swipe Views (水平分页)
最近做了一个DEMO, 是通过httpURLConnection服务来下载文件。 大致的设计思路是这样的:
1. 主Activity,显示需要下载的文件名,并通过ProgressDialog来显示下载进度。
2. 后台服务IntentService进行主要的下载操作,先通过HttpURLConnection来获取远程服务的InputStream, 然后将获取的InputStream写入设备的sdCard中。
3. 通过ResultReceiver传递下载的完成信息给ProgressDialog,使其能及时更新下载进度。
具体的代码:
1. 老样子,在AndroidManifest.xml中设置对因特网的访问权限,和对SDCard的操作权限
2. 其次,需要在AndroidManifest.xml中设置Activity和Service
3. 在DownloadActivity中,显示需要下载的文件名,点击文件名,调用DownloadService进行文件的下载,并在界面中产生ProgressDialog进度
4. DownloadService 对文件进行下载
5. 在DownloadActivity中添加DownloadReceiver类,用以接收DownloadService的下载进度信息和错误信息
附件中提供了这个DEMO的完整代码。
1. 主Activity,显示需要下载的文件名,并通过ProgressDialog来显示下载进度。
2. 后台服务IntentService进行主要的下载操作,先通过HttpURLConnection来获取远程服务的InputStream, 然后将获取的InputStream写入设备的sdCard中。
3. 通过ResultReceiver传递下载的完成信息给ProgressDialog,使其能及时更新下载进度。
具体的代码:
1. 老样子,在AndroidManifest.xml中设置对因特网的访问权限,和对SDCard的操作权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission> <uses-permission android:name="android.permission.INTERNET"></uses-permission> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
2. 其次,需要在AndroidManifest.xml中设置Activity和Service
<activity android:name="cn.sh.ideal.activity.DownloadActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <service android:name="cn.sh.ideal.service.DownloadService"/>
3. 在DownloadActivity中,显示需要下载的文件名,点击文件名,调用DownloadService进行文件的下载,并在界面中产生ProgressDialog进度
if(fileRealName!=null && fileRealName.trim().length()>0){ fileName = fileRealName; try { url = ToolsUtil.getIpAddress() + URLEncoder.encode(fileRealName,"UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } progressDialog = new ProgressDialog(DownloadActivity.this); progressDialog.setTitle(getResources().getString(R.string.download_title)); progressDialog.setMessage(getResources().getString(R.string.download_message)); progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); progressDialog.show(); intent = new Intent(DownloadActivity.this, DownloadService.class); intent.putExtra("url", url); intent.putExtra("filename", fileName); intent.putExtra("receiver", new DownloadReceiver(new Handler())); intent.setAction("start"); startService(intent); }
4. DownloadService 对文件进行下载
protected void onHandleIntent(Intent intent) { String urlToDownload = intent.getStringExtra("url"); String filenameToSave = intent.getStringExtra("filename"); ResultReceiver receiver = (ResultReceiver) intent.getParcelableExtra("receiver"); String sdPath = ""; int results = 0; String infos = ""; InputStream input = null; OutputStream output = null; try { //设备中是否存在SDCard,如果不存在则抛出异常 isSDCard(); //设备是否可连接,如果不可链接则抛出异常 isConnected(); sdPath = Environment.getExternalStorageDirectory() + "/" + Constants.DOWNLOAD_PATH; // SDCard中的存储路径是否存在,如果不存在则创建 File dir = new File(sdPath); if(!dir.exists()) createSDDir(sdPath); sdPath = Environment.getExternalStorageDirectory() + "/" + Constants.DOWNLOAD_PATH + "/" + filenameToSave; // 计算需要下载的文件的长度 long totalSize = getRemoteFilesize(urlToDownload); // 计算SDCard的剩余空间是否足够保存下载文件。如果不够,则抛出异常 isSDCardFreeSizeAvailable((int)totalSize); URL url = new URL(urlToDownload); connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(CONNECT_TIME_OUT); connection.connect(); // 获取Http服务的返回信息,如果服务信息为HTTP_OK, HTTP_PARTIAL, 则可进行下载服务,否则抛出异常 int code = getHttpResponseMessage(connection); Log.i(TAG,"httpReturnType=" + code); input = new BufferedInputStream(connection.getInputStream()); output =new FileOutputStream(sdPath); byte data[] = new byte[1024]; long total = 0l; int count; while ((count = input.read(data)) != -1) { total += count; Bundle resultData = new Bundle(); resultData.putInt("progress" ,(int) (total * 100 / totalSize)); receiver.send(UPDATE_PROGRESS, resultData); output.write(data, 0, count); } output.flush(); output.close(); input.close(); results = DOWNLOAD_SUCCESS; } catch(SDCardNotAvailableException sdex){ results = DOWNLOAD_ERROR; infos = getResources().getString(R.string.download_error_sdcard_not_available); } catch(AndroidNoActiveConnectionException aex){ results = DOWNLOAD_ERROR; infos = getResources().getString(R.string.download_error_no_active_connection); } catch(SDCardFreeNotAvailableException sdfex){ infos = getResources().getString(R.string.download_error_sdcard_not_free); results = DOWNLOAD_ERROR; } catch(HttpServiceException rex){ results = DOWNLOAD_ERROR; infos = getResources().getString(R.string.download_error_http_service); } catch(FileNotFoundException fex){ results = DOWNLOAD_ERROR; infos = getResources().getString(R.string.download_error_file_not_found); }catch(IOException ioex){ results = DOWNLOAD_ERROR; infos = getResources().getString(R.string.download_error_io); } catch(Exception ex){ results = DOWNLOAD_ERROR; infos = getResources().getString(R.string.download_error_others); Log.e(TAG,ex.getLocalizedMessage()); } finally{ if(input!=null) try { input.close(); } catch (IOException e) { e.printStackTrace(); } if(output!=null) try { output.close(); } catch (IOException e) { e.printStackTrace(); } if(connection!=null) connection.disconnect(); Bundle resultData = new Bundle(); resultData.putInt("progress" ,results); if(infos!=null && infos.trim().length()>0) resultData.putString("resultMessage", infos); receiver.send(UPDATE_PROGRESS, resultData); }
5. 在DownloadActivity中添加DownloadReceiver类,用以接收DownloadService的下载进度信息和错误信息
private class DownloadReceiver extends ResultReceiver{ public DownloadReceiver(Handler handler) { super(handler); } protected void onReceiveResult(int resultCode, Bundle resultData) { super.onReceiveResult(resultCode, resultData); if (resultCode == DownloadService.UPDATE_PROGRESS) { int progress = resultData.getInt("progress"); if(progress == DownloadService.DOWNLOAD_ERROR){ String infos = resultData.getString("resultMessage"); progressDialog.dismiss(); Toast.makeText(DownloadActivity.this, infos, Toast.LENGTH_SHORT).show(); }else if(progress == DownloadService.DOWNLOAD_SUCCESS){ progressDialog.dismiss(); }else{ progressDialog.setProgress(progress); } } }
附件中提供了这个DEMO的完整代码。
- DownloadFileDemo.rar (1.2 MB)
- 下载次数: 73
发表评论
-
android RSS reader
2013-09-26 15:04 12671. AndroidManifest.xml中的activit ... -
自定义ThreadPoolExecutor
2013-09-12 13:18 2133仍旧沿用ExecutorService的例子, 修改了Asyn ... -
关于ExecutorService的使用
2013-09-11 10:18 649ExecutorService: 线程池, 顾名思义是一个调度 ... -
Widget的开发: 一个最简单的例子
2013-06-14 10:29 1735首先,我们来说说基本概念。通常来说, 一个widget具备以下 ... -
Nofitication的使用
2013-05-22 15:16 989Notification的例子,请参考附件。 1. 创建N ... -
Contextual Action Mode
2013-05-13 16:05 2044我在网上查了N多文章, 结果发现,在ANDROID自带 ... -
GridView显示ICON和TEXT
2013-05-08 12:00 9881. 设置GridView的布局 <?xml ver ... -
Swipe Views (水平分页)
2013-05-07 13:36 15651. 创建activity public class Co ... -
ExpandableListFragment及其使用
2013-04-17 16:33 0xxxxxxxxxxxxxxx xxxxxxxxxxxx xx ... -
动态ActionBar
2013-04-17 16:32 1554首先介绍一下该应用的主要操作界面 1. ProvinceLay ... -
在DialogFragment中使用ExpandableList
2013-04-15 16:39 1487我本来想在ListFragment中使用Expanda ... -
Fragment开发实例
2013-03-15 12:15 1801SVN源码下载地址: https://svn.codespot ...
相关推荐
word版接口文档
这是一个demo,实现了安卓客服端和struts后台的交互,用json传输数据,是一个简单的例子,struts+hibernate+spring+Android;非常适合新手入门。
DWR与后台异步交互简单例子,两个JAR包,配置文件dwr.xml/web.xml
用百度的js webuploader 做的大文件上传的例子, 多线程上传,包括前台和后台代码
本程序通过CXF-Spring框架来发布一个Webservice(相当于后台,在这里访问数据库),然后由表示层C#来调用其方法。本例子所实现的是从数据库获得的数据通过webservice,显示在C#前台的DataGrid里面。CXF的jar包请本人...
把ACCESS数据库程序拆分为前台和后台(表)后,有时移动了后台(表)文件。前台程序就会打不开,所以需要程序重新链接后台表……
SWFUpload上传组件的一个完整的例子,后台由Struts2完成,有上传进度显示,可以多文件上传,如果你想使用SWFUpload组件但还不知道怎样使用,可以下载下来运行一下试试,看一下源码就知道了。
利用org.apache.commons.fileupload编写的文件上传和下载的前台和后台代码,共两个例子,个有不同,费用使用。另有用jspSmartupload制作一个文件上传和下载的例子,其制作的例子能够上传到数据库中。
1、利用org.apache.commons.fileupload编写的文件上传和下载的前台和后台代码,前台代码是Jsp,后台是用servlet处理,共2个例子,各有不同,比较使用; 2、有用jspSmartupload制作一个文件上传和下载的例子,其制作...
可可网络验证9.5版调用例子(附带后台)
1.使用jQuery实现的后台左侧下拉菜单,本例子按照后台管理的基本页面设计; 2.使用了框架,该菜单栏在左侧,右侧是相应的内容; 3.该文档兼容IE6,可以在兼容模式下正常显示和使用,并且有展开,关闭的效果; 4....
一套EASYUI的经典后台管理模板easyui的后台管理实例运行环境浏览器项目技术(必填)easyui+jquery1.4.4
uniGui例子_用UniTreeView和UniPageControl实现多文档界面.7z UniGui服务器界面汉化 .zip UniGUI结合Echarts新Demo.rar UNIGUI结合HFS.txt Unigui调用百度地图获取经纬度传递到服务器后台demo.rar unigui资源管理器....
thinkphp 例子 文档 后台管理 一个简单的后台管理例子,适合初学者学习使用。Wamp或者lamp环境要自己搭建。
websocket前端页面与后台交互的例子,解压文件后,用idea导入项目,启动WebsocketServer类,接着用浏览器打开websocket.html页面,会看到建立连接,然后在发送框输入{"id":"1","type":"yes"},返回666,输入其他信息...
一个兰色经典的网站后台摸版带PSD文件,而且做了静态的例子. 大家下载后可以看看,很有意识的一套后台网站摸版.这里就是个后台网站的样子而已.
Python3+Django2实现后台管理系统,含详细教程及数据库文件,使用 Django 我们只需要做一些配置,就可以实现简单的后台管理系统,下面我们以新闻系统为例子来搭建后台。
Stk网站后台生成系统v2.0最终版 使用方法: <br/>1.将已经建好表格的数据库文件(MDB格式)复制到Aspfile/DataTemp中,例如blog.mdb <br/>2.添加数据库,进入系统后点添加,将你网站的数据库名以及网站...