首先需要加上权限——访问网络跟存储卡:

<uses-permission android:name="android.permission.INTERNET"></uses-permission><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context=".MainActivity" >    <ProgressBar      android:id="@+id/download_main_progressBarlist"     android:layout_width="fill_parent"      android:layout_height="wrap_content"      style="?android:attr/progressBarStyleHorizontal"     />  <TextView     android:id="@+id/download_main_Text"     android:layout_width="fill_parent"     android:layout_height="wrap_content"     android:layout_alignLeft="@+id/download_main_progressBarlist"     android:layout_below="@+id/download_main_progressBarlist"     android:layout_marginTop="42dp"     android:text="当前进度" /> <Button     android:id="@+id/download_main_Button"     android:layout_width="fill_parent"     android:layout_height="wrap_content"     android:layout_alignLeft="@+id/download_main_Text"     android:layout_below="@+id/download_main_Text"     android:layout_marginTop="39dp"     android:text="下载" />"</RelativeLayout> 
MainActivity:
import java.io.File;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStream;import java.io.RandomAccessFile;import java.net.MalformedURLException;import java.net.URL;import java.net.URLConnection;import android.app.Activity;import android.os.Bundle;import android.os.Environment;import android.os.Handler;import android.os.Message;import android.util.Log;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button; import android.widget.ProgressBar;import android.widget.TextView;import android.widget.Toast;/** * 文件下载 * @author 胡汉三 * */public class MainActivity extends Activity {private static final String Path="文件的HTTP地址/ttt.mp3";private static String fileName = "ttt.mp3";private static String filePath= "/download/";private ProgressBar progressBar; private TextView textView;private Button button;private int FileLength;  private int DownedFileLength=0;private InputStream inputStream;private URLConnection connection;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);progressBar=(ProgressBar) findViewById(R.id.download_main_progressBarlist);textView=(TextView) findViewById(R.id.download_main_Text);button=(Button) findViewById(R.id.download_main_Button);button.setOnClickListener(new ButtonListener());}class ButtonListener implements OnClickListener{@Overridepublic void onClick(View v) {DownedFileLength=0;Thread thread=new Thread(){public void run(){try {DownFile(Path);} catch (Exception e) { }} };thread.start();}   }private Handler handler=new Handler(){public void handleMessage(Message msg){if (!Thread.currentThread().isInterrupted()) {switch (msg.what) {case 0:progressBar.setMax(FileLength);Log.i("文件长度----------->", progressBar.getMax()+"");  break;case 1:progressBar.setProgress(DownedFileLength);int x=DownedFileLength*100/FileLength;textView.setText(x+"%");break;case 2:Toast.makeText(getApplicationContext(), "下载完成", Toast.LENGTH_LONG).show();break;default:break;}}   }};private void DownFile(String urlString){/* * 连接到服务器 */try {URL url=new URL(urlString);connection=url.openConnection();if (connection.getReadTimeout()==5) {Log.i("---------->", "当前网络有问题");// return;}inputStream=connection.getInputStream();} catch (MalformedURLException e1) {// TODO Auto-generated catch blocke1.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}/* * 文件的保存路径和和文件名其中Nobody.mp3是在手机SD卡上要保存的路径,如果不存在则新建 */String savePAth=Environment.getExternalStorageDirectory()+filePath;File file1=new File(savePAth);if (!file1.exists()) {file1.mkdir(); }String savePathString=Environment.getExternalStorageDirectory()+filePath+fileName;File file =new File(savePathString);if (!file.exists()) { try {file.createNewFile();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}   }/* * 向SD卡中写入文件,用Handle传递线程 */Message message=new Message();try {RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rwd");randomAccessFile.setLength(FileLength);byte[]buf = new byte[1024*4];FileLength=connection.getContentLength();message.what=0;handler.sendMessage(message);int length = 0;while ((length=inputStream.read(buf))!=-1) {randomAccessFile.write(buf,0,length);DownedFileLength+=length;Log.i("-------->", DownedFileLength+"");Message message1=new Message();message1.what=1;  handler.sendMessage(message1);}inputStream.close(); randomAccessFile.close();Message message2=new Message();message2.what=2;handler.sendMessage(message2);} catch (FileNotFoundException e) {   // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}

如此这般,下载文件显示进度条就OK了





更多相关文章

  1. 【Android】向sdcard中写入文件
  2. Android 解析CSV文件,中文乱码
  3. android 打开各种文件的方式
  4. iOS、Android获取文件头信息
  5. Android通过Uri获取文件的路径的方法
  6. 【Android】使用Git控制Android程序的gitignore文件
  7. Android ListActivity实现遍历文件列表,查看文档类文件
  8. Android 动态注册监听网络变化实例详解
  9. Android 将图片文件,转成Bitmap

随机推荐

  1. aapt.AaptException Failed to crunch fi
  2. Android(安卓)TextView部分文字实现点击
  3. Android(安卓)MediaPlayer 播放本地与远
  4. android 文件的认识
  5. 极光推送和百度lbs android sdk一起使用
  6. Android(安卓)build-tools升级至23.0.0_r
  7. EditText被键盘遮住的问题
  8. 关于 Android(安卓)下的自动化测试方法介
  9. Android模拟器上进行GPS的模拟操作法
  10. android使用windows字体解决textview显示