- 浏览: 67508 次
- 性别:
- 来自: 上海
最新评论
-
kentihcai:
我这里的下载不了啊
android文件下载进度条实现 -
rabbitinhere:
程序确实是有点问题啊~~~ 2楼正解
android文件下载进度条实现 -
ssy341:
Datatables交流群
http://bbs.sailit ...
jQuery datatables使用 -
zjxkeven:
读取文件字节流时。修改成这样就没有问题了
while ((to ...
android文件下载进度条实现 -
zjxkeven:
我请求一个zip文件,后台下载文件有问题。费了好大劲才查出来。 ...
android文件下载进度条实现
做了个小例子,是关于android文件下载过程中进度条的实现,有些地方还有不当的地方,其中文件下载部分是参考mars老师的代码的,有兴趣可以去关注一下mars老师,http://www.mars-droid.com
代码写的比较乱,建议去看看mars老师的视频。
多话不说直接上代码了:
main.xml页面布局文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:id="@+id/textView" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <Button android:id="@+id/downloadTextButton" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="下载文本文件"/> <Button android:id="@+id/downloadMp3Button" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="下载MP3文件"/> <EditText android:id="@+id/editText" android:layout_width="fill_parent" android:layout_height="wrap_content" android:hint="请出输入文字!" android:lines="3"/> <Button android:id="@+id/textButton" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="测试"/> </LinearLayout>
DownloadActivity
public class DownloadActivity extends Activity { public static final int DIALOG_DOWNLOAD_PROGRESS = 0; // public int fileSize=0; // public int downloadFileSize=0; private TextView textView; private Button downloadTextButton; private Button downloadMp3Button; private Button textButton; private EditText editText; private ProgressDialog dialog = null; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); downloadTextButton = (Button) this.findViewById(R.id.downloadTextButton); downloadMp3Button = (Button) this.findViewById(R.id.downloadMp3Button); //添加监听 downloadTextButton.setOnClickListener(new DownloadTextButtonListener()); downloadMp3Button.setOnClickListener(new DownloadMp3ButtonListener()); textView = (TextView) this.findViewById(R.id.textView); editText = (EditText) this.findViewById(R.id.editText); textButton = (Button) this.findViewById(R.id.textButton); textButton.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { textView.setText(editText.getText().toString()); Toast.makeText(DownloadActivity.this, textView.getText().toString(), Toast.LENGTH_LONG); } }); } @Override protected Dialog onCreateDialog(int id) { switch(id){ case DIALOG_DOWNLOAD_PROGRESS: dialog = new ProgressDialog(this); dialog.setMessage("downloading…"); dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); dialog.setCancelable(false); dialog.show(); return dialog; default: return null; } } private Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { if(!Thread.currentThread().isInterrupted()){ switch(msg.what){ case 0: dialog.setMax(msg.arg1); break; case 1: dialog.setProgress(msg.arg1); break; case 2: dialog.dismiss(); break; case -1: String error = msg.getData().getString("error"); Toast.makeText(DownloadActivity.this, error, 1).show(); break; } } super.handleMessage(msg); } }; class DownloadTextButtonListener implements OnClickListener{ /* (non-Javadoc) * @see android.view.View.OnClickListener#onClick(android.view.View) */ @Override public void onClick(View v) { // TODO Auto-generated method stub // HttpDownloader httpDownloader = new HttpDownloader(); // String text = httpDownloader.download("http://zhangmenshiting.baidu.com/data/music/5789992/%E8%8D%B7%E5%A1%98%E6%9C%88%E8%89%B2.mp3?xcode=732ac4f76aeff611f08f3bb5c5f0aafe"); } } class DownloadMp3ButtonListener implements OnClickListener{ /* (non-Javadoc) * @see android.view.View.OnClickListener#onClick(android.view.View) */ @Override public void onClick(View v) { //打开进度条 showDialog(DIALOG_DOWNLOAD_PROGRESS); Thread t = new Thread(runnable); t.start(); } } Runnable runnable = new Runnable(){ @Override public void run() { HttpDownloader httpDownloader = new HttpDownloader(); int result = httpDownloader.download(DownloadActivity.this,"http://zhangmenshiting.baidu.com/data/music/5935874/%E6%BA%9C%E6%BA%9C%E7%9A%84%E6%83%85%E6%AD%8C.mp3?xcode=54e0a53865de98f9ba842c53eb1bf508", "music/", "e.mp3"); System.out.println(result); String str =null; if(result == 0){ str = "成功!"; }else if(result == 1){ str = "文件已存在!"; }else{ str = "失败!"; } // Toast.makeText(DownloadActivity.this, "下载结果"+str, Toast.LENGTH_LONG).show(); } }; public void sendMsg(int flag,int value){ Message message = new Message(); message.what = flag; message.arg1 = value; handler.sendMessage(message); } }
下面两个为下载的工具类:
FileUtils.java
public class FileUtils { private String SDPATH; /** * */ public FileUtils() { // TODO Auto-generated constructor stub //获得当前外部存储设备的目录 SDPATH = Environment.getExternalStorageDirectory()+"/"; } /** * 在SD卡上创建文件 * @param fileName * @return */ public File createSdFile(String fileName){ File file = new File(SDPATH + fileName); try { file.createNewFile(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return file; } /** * 创建SD卡目录 * @param dirName * @return */ public File createSDDir(String dirName){ File file = new File(SDPATH + dirName); file.mkdir(); return file; } public boolean isFileExist(String fileName){ File file = new File(SDPATH + fileName); return file.exists(); } public File writeToSDFromInput(Context context,String path,String fileName,InputStream input){ File file = null; OutputStream output = null; try { createSDDir(path); file = createSdFile(path + fileName); output = new FileOutputStream(file); byte[] buffer = new byte[4 * 1024]; int total = 0; while((input.read(buffer)) != -1){ total = total + buffer.length; output.write(buffer); //更新下载进度条 ((DownloadActivity)context).sendMsg(1,total); } output.flush(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ try { output.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //下载完成 ((DownloadActivity)context).sendMsg(2,0); return file; } }
HttpDownloader.java
public class HttpDownloader { private URL url = null; /** * 根据URL下载文件,前提是文件当中的内容为文本,返回值就是文件当中的内容 * @param urlStr * @return */ public String download(String urlStr){ StringBuffer buffer = new StringBuffer(); String line = null; BufferedReader reader = null; try { url = new URL(urlStr); try { HttpURLConnection conn = (HttpURLConnection) url.openConnection(); reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((line = reader.readLine()) != null) { buffer.append(line); } } catch (IOException e) { Log.e("io", "HttpURLConnection -> IOException"); e.printStackTrace(); } } catch (MalformedURLException e) { Log.e("url","url -> MalformedURLException"); e.printStackTrace(); }finally{ try { reader.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return buffer.toString(); } /** * 该函数返回整形: -1代表下载出错,0代表下载成功,1代表下载文件已存在 * @param urlStr * @param path * @param fileName * @return */ public int download(Context context,String urlStr,String path,String fileName){ InputStream input = null; FileUtils fileUtils = new FileUtils(); if(fileUtils.isFileExist(path + fileName)){ ((DownloadActivity)context).sendMsg(2,0); return 1; }else{ try { input = getInputStreamFromUrl(context,urlStr); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } File resultFile = fileUtils.writeToSDFromInput(context,path, fileName, input); if(resultFile == null){ return -1; } } return 0; } public InputStream getInputStreamFromUrl(Context context,String urlStr) throws IOException{ url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); InputStream s = conn.getInputStream(); ((DownloadActivity)context).sendMsg(0,conn.getContentLength()); return s; } }
别忘记添加:
<uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
下面是运行的结果图:
正在下载:
下载完成之后,我们在sdcard/music可以看到f.mp3文件
下面附上源码,可以自己修改,在例子中我是通过直接弹出的方式显示进度条的,这样在下载的时候我们就不能做其他的事情了,我们可以在布局文件中显示进度条,这样我们在下载的时候可以在文本框中输入一下内容,点击测试按钮之后文本框中的内容可以在上面的TextView中显示出来。
如果运行本例子,需要更改下载的url地址,我用的是百度的音乐下载,在测试中发现百度每次生成的连接只能下载一次。
评论
4 楼
kentihcai
2014-08-11
我这里的下载不了啊
3 楼
rabbitinhere
2014-06-18
程序确实是有点问题啊~~~ 2楼正解
2 楼
zjxkeven
2012-09-18
读取文件字节流时。修改成这样就没有问题了
while ((total = input.read(buffer)) != -1) {
output.write(buffer, 0, total);
}
希望能帮助大家。
while ((total = input.read(buffer)) != -1) {
output.write(buffer, 0, total);
}
希望能帮助大家。
1 楼
zjxkeven
2012-09-18
我请求一个zip文件,后台下载文件有问题。费了好大劲才查出来。跟大家分享一下
发表评论
-
系统设置更改时间onConfigurationChanged
2011-08-13 12:15 1259在前一个例子中我们看到了屏幕方向的更改,事实上,当屏幕方向改变 ... -
android动态更改屏幕方向
2011-08-13 11:59 6625在androd中要通过程序改变屏幕显示的方向,必须覆盖setR ... -
Android - LayoutInflater 的使用
2011-08-05 09:10 940LayoutInflater is used to insta ... -
使用Shader渲染图形
2011-07-29 17:29 1510public class ShaderActivity ext ... -
android动画
2011-07-29 15:45 1212在Android系统中系统了两种动画实现方式:一种是Tween ... -
SQLite
2011-07-29 10:16 1926Android中通过SQLite数据库引擎来实现结构化数据 ... -
(转)android listview滑动时加载(动态加载)
2011-07-28 16:18 1777如果adapter中的数据量很大的时候,在加载listv ... -
Android-Intent和PendingIntent的关系
2011-07-28 16:03 991本文转自:http://yinter.iteye.com/bl ... -
Broadcast Receiver处理广播事件
2011-07-28 13:56 2556本实例介绍自定义Broadcast Receiver和系统 ... -
Service实例
2011-07-28 10:04 923下面通过一个实例演示如何创建、启动、停止及绑定一个Servic ... -
菜单Menu
2011-07-27 17:07 912本实例主要介绍了android中的一些菜单,Android系 ... -
ListView组件与SimpleAdapter
2011-07-27 16:34 1960记录两个ListView的简单小例子.其中使用到 了Simpl ... -
WebView与ProgressDialog结合
2011-07-27 16:18 3152WebView组件支持直接加载网页,可以将其视为一个浏览器,要 ...
相关推荐
\Android文件下载进度条的实现.txt\Android文件下载进度条的实现.txt
实现文件的复制 及 进度条的显示 progressdialog
Android实现多文件的下载,显示进度条
这是本人初学android制作的一个下载单个文件实现进度条时时更新
我们今天开始学习的是下载...文件下载进度条控制(就是为了高清壁纸加个进度条),自己研究了好久,但是进度条只能显示缓存写入文件的进度,不能显示下载进度。找了好久,终于找到一段用的代码,所以记录下来,大家分享
后台service实现文件下载,通过广播前台显示进度,文件下载方法就不写进去了,网上都有
本文实例为大家分享了android实现音乐播放器进度条效果的具体代码,供大家参考,具体内容如下 效果图 依赖3个对象 MediaPlayer:实现音乐播放,暂停,缓冲。 SeekBar:滑动的进度条。 java.util.Timer:定时器,时时...
最近做滴文件上传,可以实现单文件上传还有进度条的百分比显示哈,给大家分享下
一个简单实现的自定义圆环进度条,可使用于文件的上传下载图片加载等地方.
Android 使用HttpClient和第三方MiME文件上传类库,实现文件上传带进度条。 注:这个是自己写的,亲测没有问题。
本篇文章主要介绍了android中实现OkHttp下载文件并带进度条,OkHttp是比较火的网络框架,它支持同步与异步请求,支持缓存,可以拦截,更方便下载大文件与上传文件的操作,有兴趣的可以了解一下
通过在style文件中进行配置,实现了带文字竖直进度条 类似电量显示的功能。
实现一个带进度条的下载: 1.下载前获得文件的总长 2.下载的过程中对已经下载的长度进行累加,不断发送消息更新进度条 3.下载完成后发送的消息
基于HttpClient的轻量级封装,并提供了文件上传进度显示的接口,直接对httpmime源码进行改造,不包含任何第三方jar包。
基于zip4j开源框架实现android解压带有密码的zip文件(进度条显示),项目中有jar包,非常好用。解压、压缩、压缩添加密码、解压带有密码的zip都可以使用。
主要介绍了Android实现文件上传和下载倒计时功能的圆形进度条,需要的朋友可以参考下
主要为大家详细介绍了Android实现百分比下载进度条效果,具有一定的参考价值,感兴趣的小伙伴们可以参考一下