做了个小例子,是关于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(){@Overridepublic void onClick(View v) {textView.setText(editText.getText().toString());Toast.makeText(DownloadActivity.this, textView.getText().toString(), Toast.LENGTH_LONG);}                });            }    @Overrideprotected 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(){@Overridepublic 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) */@Overridepublic 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) */@Overridepublic void onClick(View v) {//打开进度条showDialog(DIALOG_DOWNLOAD_PROGRESS);Thread t = new Thread(runnable);t.start();}        }        Runnable runnable = new Runnable(){@Overridepublic 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 blocke.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 blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{try {output.close();} catch (IOException e) {// TODO Auto-generated catch blocke.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 blocke.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 blocke.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地址,我用的是百度的音乐下载,在测试中发现百度每次生成的连接只能下载一次。

更多相关文章

  1. android asmack 注册 登陆 聊天 多人聊天室 文件传输
  2. Android开发配置篇——Eclipse配置
  3. android中的数据存取 之 File
  4. [置顶] Android必须知道的框架-NoHttp
  5. 安卓SDK接入Unity
  6. Android(安卓)SearchView
  7. cocos打包android遇到的那些坑
  8. Android基础(八):文件存储
  9. android 下修改 hosts文件 及 out of memory的解决

随机推荐

  1. android 把bitmap转成drawble后宽高不一
  2. andriod 动态设置TextView 和 RelativeLa
  3. Android中实现可滑动的Tab的3种方式
  4. Android(安卓)对text文本内容添加下划线
  5. Android(安卓)手机获取Mac地址的几种方法
  6. android抽屉效果的实现
  7. Android(安卓)ViewPager简单实现 - 倒计
  8. 【AS-AndroidX】AndroidX迁移-支持依赖库
  9. 关于LayoutParams的使用经验
  10. android 检测当前网络并调用系统设置