Skip to content

Instantly share code, notes, and snippets.

@hanigamal
Forked from alexjlockwood/AccountUtils.java
Created January 3, 2013 02:07
Show Gist options
  • Save hanigamal/4440177 to your computer and use it in GitHub Desktop.
Save hanigamal/4440177 to your computer and use it in GitHub Desktop.
import android.accounts.Account;
import android.accounts.AccountManager;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Build;
import android.preference.PreferenceManager;
public final class AccountUtils {
private static final String KEY_ACCOUNT_NAME = "account_name";
public static Account getGoogleAccountByName(Context ctx, String accountName) {
if (accountName != null) {
AccountManager am = AccountManager.get(ctx);
Account[] accounts = am.getAccountsByType(GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE)
for (Account account : accounts) {
if (accountName.equals(account.name)) {
return account;
}
}
}
return null;
}
public static String getAccountName(Context ctx) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx);
return prefs.getString(KEY_ACCOUNT_NAME, null);
}
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public static void setAccountName(Context ctx, String accountName) {
Editor editor = PreferenceManager.getDefaultSharedPreferences(ctx).edit();
editor.putString(KEY_ACCOUNT_NAME, accountName);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
editor.apply();
} else {
editor.commit();
}
}
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public static void removeAccount(Context ctx) {
Editor editor = PreferenceManager.getDefaultSharedPreferences(ctx).edit();
editor.remove(KEY_ACCOUNT_NAME);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
editor.apply();
} else {
editor.commit();
}
}
}
public class AuthorizedTask extends AsyncTask<Void, Void, Response> {
private AuthActivity mActivity;
private String mAccountName;
private Request mRequest;
AuthorizedTask(AuthActivity activity, String accountName, Request request) {
mActivity = activity;
mAccountName = accountName;
mRequest = request;
}
/**
* Get a authentication token if one is not available. If the error is not
* recoverable then it displays the error message on parent activity right
* away.
*/
@Override
protected Response doInBackground(Void... params) {
try {
String token = GoogleAuthUtil.getToken(mActivity, mAccountName, mRequest.scope);
return NetworkUtils.doPost(mRequest, token);
} catch (GooglePlayServicesAvailabilityException e) {
// GooglePlayServices.apk is either old, disabled, or not present.
mActivity.showErrorDialog(e.getConnectionStatusCode());
} catch (UserRecoverableAuthException e) {
// Unable to authenticate, so try to recover.
mActivity.startActivityForResult(e.getIntent(),
AuthActivity.REQUEST_CODE_RECOVER_PLAY_SERVICES_ERROR);
} catch (GoogleAuthException e) {
Log.e(TAG, "Unrecoverable error: " + e.getMessage());
// TODO: figure out how to react to this error
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
// TODO: figure out how to react to this error (exponential backoff?)
}
return null;
}
import java.io.IOException;
import android.os.AsyncTask;
import android.util.Log;
import com.alexjlockwood.gcmdemo.http.Request;
import com.alexjlockwood.gcmdemo.http.Response;
import com.google.android.gms.auth.GoogleAuthException;
import com.google.android.gms.auth.GoogleAuthUtil;
import com.google.android.gms.auth.GooglePlayServicesAvailabilityException;
import com.google.android.gms.auth.UserRecoverableAuthException;
public class AuthTask extends AsyncTask<Void, Void, Response> {
private static final String TAG = "AuthorizedTask";
private AuthActivity mActivity;
private String mAccountName;
private Request mRequest;
AuthorizedTask(AuthActivity activity, String accountName, Request request) {
mActivity = activity;
mAccountName = accountName;
mRequest = request;
}
/**
* Get a authentication token if one is not available. If the error is not
* recoverable then it displays the error message on parent activity right
* away.
*/
@Override
protected Response doInBackground(Void... params) {
try {
String token = GoogleAuthUtil.getToken(mActivity, mAccountName, mRequest.scope);
return NetworkUtils.doPost(mRequest, token);
} catch (GooglePlayServicesAvailabilityException e) {
// GooglePlayServices.apk is either old, disabled, or not present.
mActivity.showErrorDialog(e.getConnectionStatusCode());
} catch (UserRecoverableAuthException e) {
// Unable to authenticate, so try to recover.
mActivity.startActivityForResult(e.getIntent(),
AuthActivity.REQUEST_CODE_RECOVER_PLAY_SERVICES_ERROR);
} catch (GoogleAuthException e) {
Log.e(TAG, "Unrecoverable error: " + e.getMessage());
// TODO: figure out how to react to this error
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
// TODO: figure out how to react to this error (exponential backoff?)
}
return null;
}
}
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public final class NetworkUtils {
public Response doPost(Request request, String token) throws IOException {
URL url = request.url;
Map<String, List<String>> headers = request.headers;
Map<String, String> bodyParams = request.bodyParams;
byte[] body = constructBody(bodyParams);
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) url.openConnection();
addHeaders(conn, token, headers);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setFixedLengthStreamingMode(body.length);
conn.setRequestMethod("POST");
// post the request
OutputStream out = conn.getOutputStream();
out.write(body);
out.close();
// handle the response
BufferedInputStream in = new BufferedInputStream(conn.getInputStream());
int status = conn.getResponseCode();
if ((status / 100) == 2) {
return new Response(status, conn.getHeaderFields(), readStream(in));
} else {
// apparently 401/403 never come here
BufferedInputStream err = new BufferedInputStream(conn.getErrorStream());
return new Response(status, conn.getHeaderFields(), readStream(err));
}
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
public static void addHeaders(HttpURLConnection conn, String token, Map<String, List<String>> headers) {
conn.addRequestProperty("Authorization", "OAuth " + token);
if (headers != null) {
for (String header : headers.keySet()) {
for (String value : headers.get(header)) {
conn.addRequestProperty(header, value);
}
}
}
}
public static byte[] constructBody(Map<String, String> bodyParams) {
// Constructs the POST body using the parameters
StringBuilder bodyBuilder = new StringBuilder();
Iterator<Entry<String, String>> iterator = bodyParams.entrySet().iterator();
while (iterator.hasNext()) {
Entry<String, String> param = iterator.next();
bodyBuilder.append(param.getKey()).append('=').append(param.getValue());
if (iterator.hasNext()) {
bodyBuilder.append('&');
}
}
return bodyBuilder.toString().getBytes();
}
public static byte[] readStream(InputStream in) throws IOException {
final byte[] buf = new byte[1024];
int count = 0;
ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
while ((count = in.read(buf)) != -1) {
out.write(buf, 0, count);
}
in.close();
return out.toByteArray();
}
}
import java.net.URL;
import java.util.List;
import java.util.Map;
public class Request {
public URL url;
public Map<String, List<String>> headers;
public String accountName;
public Map<String, String> bodyParams; // non-null if POST
public String scope;
public ResponseHandler handler;
private Request(URL url, Map<String, List<String>> headers, Map<String, String> bodyParams,
String accountName, String scope) {
this.url = url;
this.headers = headers;
this.accountName = accountName;
this.bodyParams = bodyParams;
this.scope = scope;
}
public static Request makeGet(URL url, Map<String, List<String>> headers, String accountName, String scope) {
return new Request(url, headers, null, accountName, scope);
}
public static Request makePost(URL url, Map<String, List<String>> headers,
String accountName, Map<String, String> body, String scope) {
return new Request(url, headers, body, accountName, scope);
}
}
import java.util.List;
import java.util.Map;
public class Response {
public int statusCode;
public Map<String, List<String>> headers;
public byte[] body;
public Response(int statusCode, Map<String, List<String>> headers, byte[] body) {
this.statusCode = statusCode;
this.headers = headers;
this.body = body;
}
public Response(int statusCode, Map<String, List<String>> headers, String body) {
this.statusCode = statusCode;
this.headers = headers;
this.body = body.getBytes();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment