Monday, April 15, 2013

[Code snippets] Download 1 HTTP file với progess notification

try {
// Khai báo url
URL url = new URL("http://somewhere.com/some/webhosted/file");

//tạo HTTP connection
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

//setup phương thức cho HTTP connecton
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);

// kết nối
urlConnection.connect();


// khởi tạo sdcard . Lưu ý phương thức Environment.getExternalStorageDirectory(); trả lại đường dẫn đến sdcard
File SDCardRoot = Environment.getExternalStorageDirectory();
// Tạo 1 file để lưu nội dung trang web
File file = new File(SDCardRoot,"somefile.ext");

//Khai báo FileInputStream để tương tác với InputStream
FileOutputStream fileOutput = new FileOutputStream(file);

//InputStream để đọc dẽ liệu từ url
InputStream inputStream = urlConnection.getInputStream();

//lấy size của dữ liệu tải về
int totalSize = urlConnection.getContentLength();
// khai báo 1 biến để biết dữ liệu tải về ( realtime)
int downloadedSize = 0;

//tạo buffer
byte[] buffer = new byte[1024];
int bufferLength = 0; //used to store a temporary size of the buffer

//đọc dữ liệu từ buffer
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
//ghi từ buffer vào textfile ở sdcard
fileOutput.write(buffer, 0, bufferLength);
//update downloadSize
downloadedSize += bufferLength;
//dựa vào biến downloadSize để update progess
updateProgress(downloadedSize, totalSize);

}
//đóng outputstream khi hoàn thành
fileOutput.close();

} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

No comments:

Post a Comment