summaryrefslogtreecommitdiff
path: root/src/de/danoeh/antennapod/util/ConnectionTester.java
blob: 8d5e189f424b1c9882c47565cfb4418a4170c5ef (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
package de.danoeh.antennapod.util;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import de.danoeh.antennapod.BuildConfig;

import android.content.Context;
import android.util.Log;

/** Tests a connection before downloading something. */
public class ConnectionTester implements Runnable {
	private static final String TAG = "ConnectionTester";
	private String strUrl;
	private Context context;
	private int connectTimeout;
	private int readTimeout;
	private Callback callback;
	private int reason;
	
	public ConnectionTester(String url, Context context, Callback callback) {
		super();
		this.strUrl = url;
		this.context = context;
		this.callback = callback;
		connectTimeout = 500;
		readTimeout = connectTimeout;
	}



	@Override
	public void run() {
		if (BuildConfig.DEBUG) Log.d(TAG, "Testing connection");
		try {		
			URL url = new URL(strUrl);
	        HttpURLConnection con = (HttpURLConnection) url.openConnection();
	        con.connect();
	        callback.onConnectionSuccessful();
	        if (BuildConfig.DEBUG) Log.d(TAG, "Connection seems to work");
		} catch (MalformedURLException e) {
			e.printStackTrace();
			reason = DownloadError.ERROR_CONNECTION_ERROR;
			if (BuildConfig.DEBUG) Log.d(TAG, "Connection failed");
			callback.onConnectionFailure();
		} catch (IOException e) {
			e.printStackTrace();
			reason = DownloadError.ERROR_CONNECTION_ERROR;
			if (BuildConfig.DEBUG) Log.d(TAG, "Connection failed");
			callback.onConnectionFailure();
		}
	}
	
	
	public static abstract class Callback {
		public abstract void onConnectionSuccessful();
		public abstract void onConnectionFailure();
	}
	
	public int getReason() {
		return reason;
	}


}