aboutsummaryrefslogtreecommitdiff
path: root/src/org/happysanta/gd/API/DownloadFile.java
blob: 2920c278a33a41f662502a29c2cfa50907685dd3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
package org.happysanta.gd.API;

import android.content.Context;
import android.os.AsyncTask;
import android.os.PowerManager;
import org.apache.http.HttpException;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import static org.happysanta.gd.Helpers.getGDActivity;

public class DownloadFile {

	private String urlString;
	private DownloadHandler handler;
	private FileOutputStream output;
	private AsyncDownloadTask task;

	public DownloadFile(String url, FileOutputStream output) {
		this.urlString = url;
		this.output = output;
	}

	public DownloadFile(String url, FileOutputStream output, DownloadHandler handler) {
		this(url, output);
		this.handler = handler;
	}

	public void setDownloadHandler(DownloadHandler handler) {
		this.handler = handler;
	}

	public void start() {
		task = new AsyncDownloadTask();
		task.execute();
	}

	public void cancel() {
		if (task != null) {
			task.cancel(true);
			task = null;
		}
	}

	protected class AsyncDownloadTask extends AsyncTask<Void, Integer, Throwable> {

		private PowerManager.WakeLock lock;

		@Override
		protected Throwable doInBackground(Void... params) {
			// OutputStream output = (FileOutputStream)params[1];
			InputStream input = null;
			HttpURLConnection connection = null;

			try {
				URL url = new URL(urlString);
				connection = (HttpURLConnection) url.openConnection();
				connection.connect();

				// expect HTTP 200 OK, so we don't mistakenly save error report
				// instead of the file
				if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
					return new HttpException("Server returned HTTP " + connection.getResponseCode()
							+ " " + connection.getResponseMessage());
				}

				// this will be useful to display download percentage
				// might be -1: server did not report the length
				int fileLength = connection.getContentLength();

				// download the file
				input = connection.getInputStream();

				byte data[] = new byte[4096];
				long total = 0;
				int count;
				while ((count = input.read(data)) != -1) {
					// allow canceling with back button
					if (isCancelled()) {
						input.close();
						return null;
					}

					total += count;

					// publishing the progress....
					if (fileLength > 0) // only if total length is known
						publishProgress((int) (total * 100 / fileLength));

					output.write(data, 0, count);
				}
			} catch (Exception e) {
				return e;
			} finally {
				try {
					if (output != null)
						output.close();
					if (input != null)
						input.close();
				} catch (IOException ignored) {
				}

				if (connection != null)
					connection.disconnect();
			}

			return null;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();

			// take CPU lock to prevent CPU from going off if the user
			// presses the power button during download
			PowerManager pm = (PowerManager) getGDActivity().getSystemService(Context.POWER_SERVICE);
			lock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
					getClass().getName());
			lock.acquire();

			handler.onStart();
		}

		@Override
		protected void onProgressUpdate(Integer... progress) {
			super.onProgressUpdate(progress);

			handler.onProgress(progress[0]);
		}

		@Override
		protected void onPostExecute(Throwable error) {
			lock.release();
			handler.onFinish(error);
		}

	}


}