Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.sajmon.imagedownload;
- import java.io.IOException;
- import java.io.InputStream;
- import java.net.HttpURLConnection;
- import java.net.MalformedURLException;
- import java.net.URL;
- import android.app.IntentService;
- import android.content.Intent;
- import android.os.Bundle;
- import android.os.ResultReceiver;
- public class DownloadService extends IntentService {
- protected final byte[] BUFFER = new byte[1024];
- protected static final int PROGRESS_UPDATE = 1345;
- public DownloadService() {
- super("DownloadService");
- }
- protected void onHandleIntent(Intent intent) {
- String urlLink = intent.getStringExtra("url");
- ResultReceiver receiver = intent.getParcelableExtra("receiver");
- HttpURLConnection con = null;
- InputStream input = null;
- long contentLength;
- long total = 0;
- int downloaded = 0;
- long start = 0, end = 0;
- start = System.currentTimeMillis();
- try {
- URL url = new URL(urlLink);
- con = (HttpURLConnection) url.openConnection();
- con.connect();
- if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {
- contentLength = con.getContentLength();
- input = con.getInputStream();
- while ((downloaded = input.read(BUFFER)) != -1) {
- total += downloaded;
- Bundle data = new Bundle();
- data.putInt("progress", (int) (total * 100 / contentLength));
- //publishing progress
- receiver.send(PROGRESS_UPDATE, data);
- }
- end = System.currentTimeMillis();
- Bundle data = new Bundle();
- data.putInt("progress", 100);
- data.putLong("time", end - start);
- receiver.send(PROGRESS_UPDATE, data);
- }
- }
- catch (MalformedURLException e) {
- e.printStackTrace();
- }
- catch (IOException e) {
- e.printStackTrace();
- }
- finally {
- if (input != null) {
- try {
- input.close();
- }
- catch (IOException e) {
- e.printStackTrace();
- }
- }
- if (con != null) {
- con.disconnect();
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment