《android文件下载及进度条.docx》由会员分享,可在线阅读,更多相关《android文件下载及进度条.docx(11页珍藏版)》请在三一办公上搜索。
1、android 文件下载及进度条Android sdk 3.0 编译通过 package com.download; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import .URL; import .URLConnection; import org.apache.http.client.ClientProtocolException; import android.app.Activity; import andr
2、oid.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 and
3、roid.widget.Toast; public class AndroidDownLoadActivity extends Activity private Button DownloadTextButton = null; private Button DownloadMp3Button = null; ProgressBar pb; TextView tv; int fileSize; int downLoadFileSize; String fileEx, fileNa, filename; private Handler handler = new Handler Override
4、 public void handleMessage(Message msg) / 定义一个Handler,用于处理下载线程与UI间通讯 if (!Thread.currentThread.isInterrupted) ; switch (msg.what) case 0: pb.setMax(fileSize); case 1: pb.setProgress(downLoadFileSize); int result = downLoadFileSize * 100 / fileSize; tv.setText(result + %); break; case 2: Toast.makeTe
5、xt(AndroidDownLoadActivity.this, 文件下载完成, 1) .show; break; case -1: String error = msg.getData.getString(error); Toast.makeText(AndroidDownLoadActivity.this, error, 1) .show; break; super.handleMessage(msg); /* * down load file to sdcard. */ public void down_file(String url, String path) throws IOExc
6、eption / 下载函数 filename = url.substring(url.lastIndexOf(/) + 1); / 获取文件名 URL myURL = new URL(url); URLConnection conn = myURL.openConnection; conn.connect; InputStream is = conn.getInputStream; this.fileSize = conn.getContentLength;/ 根据响应获取文件大小 Log.i(value, length = + this.fileSize); if (this.fileSiz
7、e = 0) throw new RuntimeException(无法获知文件大小 ); if (is = null) throw new RuntimeException(stream is null); File file = new File(Environment.getExternalStorageDirectory, filename); FileOutputStream fos = new FileOutputStream(file); / 把数据存入路径+文件名 byte buf = new byte1024; downLoadFileSize = 0; sendMsg(0)
8、; do / 循环读取 int numread = is.read(buf); if (numread = -1) break; fos.write(buf, 0, numread); downLoadFileSize += numread; sendMsg(1);/ 更新进度条 while (true); sendMsg(2);/ 通知下载完成 try is.close; catch (Exception ex) Log.e(tag, error: + ex.getMessage, ex); private void sendMsg(int flag) Message msg = new M
9、essage; msg.what = flag; handler.sendMessage(msg); /* Called when the activity is first created. */ Override public void onCreate(Bundle savedInstanceState) super.onCreate(savedInstanceState); setContentView(R.layout.main); private class DownTextButtonListener implements OnClickListener public void
10、onClick(View v) super.onCreate(savedInstanceState); setContentView(R.layout.main); pb = (ProgressBar) findViewById(R.id.down_pb); tv = (TextView) findViewById(R.id.tv); new Thread public void run try down_file( .start; http:/下载路径 , /sdcard/); / 下载文件,参数:第一个URL,第二个存放路径 catch (ClientProtocolException e
11、) / TODO Auto-generated catch block e.printStackTrace; catch (IOException e) / TODO Auto-generated catch block e.printStackTrace; DownloadTextButton = (Button) findViewById(R.id.DownTextButtonId); DownloadTextButton.setOnClickListener(new DownTextButtonListener); DownloadMp3Button = (Button) findVie
12、wById(R.id.DownMp3ButtonId); DownloadMp3Button.setOnClickListener(new DownMp3ButtonListener); Thread thread = new Thread(new Runnable public void run / TODO Auto-generated method stub HttpDownloader httpDownloader = new HttpDownloader; String irc = httpDownloader .download(http:/下载路径 ,); System.out.
13、println(irc); ); thread.start; private class DownMp3ButtonListener implements OnClickListener public void onClick(View v) Thread thread = new Thread(new Runnable public void run / TODO Auto-generated method stub HttpDownloader httpDownloader = new HttpDownloader; int result = httpDownloader .downFil
14、e( http:/下载路径 , test/, love.exe); System.out.println(result); ); thread.start; package com.download; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import .HttpURLConnection; import .MalformedURLException;
15、 import .URL; import .URLConnection; import android.util.Log; public class HttpDownloader private URL url = null; public String download(String urlStr) StringBuffer sb = new StringBuffer; String line = null; BufferedReader buffer = null; try / 创建一个url对象 url = new URL(urlStr); / 创建一个Http连接对象 /HttpURL
16、Connection urlConn = (HttpURLConnection) url.openConnection; URLConnection urlConn = url.openConnection; urlConn.connect; int fileSize = urlConn.getContentLength;/ 根据响应获取文件大小 Log.d(filesize , * + fileSize); / 使用IO流读取数据 buffer = new BufferedReader(new InputStreamReader(urlConn .getInputStream); while
17、 (line = buffer.readLine) != null) sb.append(line); catch (Exception e) e.printStackTrace; finally try buffer.close; catch (Exception e) e.printStackTrace; return sb.toString; public int downFile(String urlStr, String path, String fileName) InputStream inputStream = null; try FileUtils fileUtils = n
18、ew FileUtils; if (fileUtils.isFileExist(path + fileName) return 1; else inputStream = getInputStreamFromUrl(urlStr); File resultFile = fileUtils.write2SDFromInput(path, fileName, inputStream); if (resultFile = null) return -1; catch (Exception e) e.printStackTrace; return -1; finally try inputStream
19、.close; catch (Exception e) e.printStackTrace; return 0; private InputStream getInputStreamFromUrl(String urlStr) throws MalformedURLException, IOException / TODO Auto-generated method stub url = new URL(urlStr); HttpURLConnection urlConn = (HttpURLConnection) url.openConnection; InputStream inputSt
20、ream = urlConn.getInputStream; return inputStream; package com.download; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import android.os.Environment; public class FileUtils private String SDPATH; public Stri
21、ng getSDPATH return SDPATH; public FileUtils SDPATH = Environment.getExternalStorageDirectory + /; public File createSDFile(String filename) throws IOException File file = new File(SDPATH + filename); file.createNewFile; return file; public File createSDDir(String dirname) throws IOException File fi
22、le = new File(SDPATH + dirname); file.mkdir; return file; public boolean isFileExist(String fileName) File file = new File(SDPATH + fileName); return file.exists; public File write2SDFromInput(String path, String fileName, InputStream input) File file = null; OutputStream output = null; try createSD
23、Dir(path); file = createSDFile(path + fileName); output = new FileOutputStream(file); byte buffer = new byte4 * 1024; while (input.read(buffer) != -1) output.write(buffer); output.flush; catch (Exception e) e.printStackTrace; finally try output.close; catch (Exception e) e.printStackTrace; return file; Main.xml Manifest.xml