android 檔案下載下傳
進度條:
ProgressDialog progress = new ProgressDialog(context);
progress.setTitle(“檔案下載下傳”);
progress.setMessage("loading...");
progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progress.setIndeterminate(false);//設定為fase等待進度更新,設定為true則左右循環滾動
progress.setMax(100);
下載下傳部分
HttpURLConnection conn = null;
URL url = null;
url = new URL(connStr);//connStr,通路路徑
conn = url.openConnection();
long size = conn.getContentLength();//檔案大小
BufferedInputStream in = new BufferedInputStream(conn.openStream());
ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
BufferedOutputStream out = new BufferedOutputStream(dataStream);
int count = 0;
long total = 0L;
byte[] data = new byte[512];
while((count = in.read(data)) != -1){
total += count;
publishProgress((int)(total*100/size));//放在Asycntask裡面做進度條更新;
out.write(data,0,count);
}
out.flush();
byte[] bytes = dataStream.toByteArray();
String s = new String(bytes);//轉換成對應的類型
return s;