記得因為用到網路跟寫入檔案
所以要在 AndroidManifest.xml 增加 2 個 permission
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Activity 的內容
@Override
protected void onCreate(Bundle savedInstanceState) {
................................................................................
new getMsgTask().execute("http://URL/file1", "http://http://URL/file2");
}
class getMsgTask extends AsyncTask<String, Void , String>{
public int iFileSize = 0;
private int dReadSum = 0;
@Override
//strUrlFile是一個array..可以帶入很多個參數
protected String doInBackground(String... strUrlFile){
URL urlFileLocation = null;
HttpURLConnection connFile = null;
String ret = "";
try{
int iUrlCount = strUrlFile.length;
FileOutputStream output = null;
for (int i =0 ; i < iUrlCount ; i++){
urlFileLocation = new URL(strUrlFile[i]);
connFile = (HttpURLConnection) urlFileLocation.openConnection();
connFile.setDoInput(true);
String fileName = strUrlFile[i].substring(strUrlFile[i].lastIndexOf("/")+1);
//用 android.os.Environment.getExternalStorageDirectory().getPath() 取得 "/sdcard"
output = new FileOutputStream(android.os.Environment.getExternalStorageDirectory().getPath() + fileName);
InputStream is = connFile.getInputStream();
iFileSize = connFile.getContentLength();
byte[] buffer = new byte[1024];
int len1 = 0;
dReadSum = 0;
while ( (len1 = is.read(buffer)) != -1) {
output.write(buffer, 0, len1);
//dReadSum += len1;
//publishProgress(dReadSum*100/iFileSize);
}
output.close();
is.close();
ret += "File"+ (i+1) +" 完成\n";
}
}catch(Exception e){
ret += "download---"+ e.toString();
}
return ret;
}
@Override
protected void onPreExecute() {
//在 doInBackground 開始之前的 process
super.onPreExecute();
}
protected void onPostExecute(String result) {
//在 doInBackground 完成以後接續的 process
super.onPostExecute(result);
TextView tv = (TextView)findViewById(R.id.msg);
tv.setText(result);
}
@Override
protected void onProgressUpdate(Void... values) {
//此 method 是在呼叫 publishProgress() 時才會trigger
//配合 progressBar 來使用
super.onProgressUpdate(values);
}
}