summaryrefslogtreecommitdiff
path: root/src/de/danoeh/antennapod/asynctask/FlattrTokenFetcher.java
blob: b56e83d2524d64632bef5e3e082a4465bcee8d67 (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
package de.danoeh.antennapod.asynctask;


import org.shredzone.flattr4j.exception.FlattrException;
import org.shredzone.flattr4j.oauth.AccessToken;
import org.shredzone.flattr4j.oauth.AndroidAuthenticator;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import de.danoeh.antennapod.AppConfig;
import de.danoeh.antennapod.R;
import de.danoeh.antennapod.activity.FlattrAuthActivity;
import de.danoeh.antennapod.util.flattr.FlattrUtils;

/** Fetches the access token in the background in order to avoid networkOnMainThread exception. */

public class FlattrTokenFetcher extends AsyncTask<Void, Void, AccessToken> {
	private static final String TAG = "FlattrTokenFetcher";
	Context context;
	AndroidAuthenticator auth;
	AccessToken token;
	Uri uri;
	ProgressDialog dialog;
	FlattrException exception;
	
	public FlattrTokenFetcher(Context context, AndroidAuthenticator auth, Uri uri) {
		super();
		this.context = context;
		this.auth = auth;
		this.uri = uri;
	}

	@Override
	protected void onPostExecute(AccessToken result) {
		if (result != null) {
			FlattrUtils.storeToken(result);
		}
		dialog.dismiss();
		if (exception == null) {
			FlattrAuthActivity instance = FlattrAuthActivity.getInstance();
			if (instance != null) {
				instance.handleAuthenticationSuccess();
			} else {
				Log.e(TAG, "FlattrAuthActivity instance was null");
			}
		} else {
			FlattrUtils.showErrorDialog(context, exception.getMessage());
		}
	}



	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		dialog = new ProgressDialog(context);
		dialog.setMessage(context.getString(R.string.processing_label));
		dialog.setIndeterminate(true);
		dialog.setCancelable(false);
		dialog.show();			
	}



	@Override
	protected AccessToken doInBackground(Void... params) {
		try {
			token = auth.fetchAccessToken(uri);
		} catch (FlattrException e) {
			e.printStackTrace();
			exception = e;
			return null;
		}
		if (token != null) {
			if (AppConfig.DEBUG) Log.d(TAG, "Successfully got token");
			return token;
		} else {
			Log.w(TAG, "Flattr token was null");
			return null;
		}
	}

	@SuppressLint("NewApi")
	public void executeAsync() {
		if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.GINGERBREAD_MR1) {
			executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
		} else {
			execute();
		}
	}
	
}