Skip to content

Instantly share code, notes, and snippets.

@doneill
Created September 26, 2013 00:08
Show Gist options
  • Select an option

  • Save doneill/6708038 to your computer and use it in GitHub Desktop.

Select an option

Save doneill/6708038 to your computer and use it in GitHub Desktop.
Authenticate OAuth2 ArcGIS Services in Android
public class WebViewDialogFragment extends DialogFragment {
// The redirect_uri can be either a special value of urn:ietf:wg:oauth:2.0:oob
// or an application-specific custom URI that is handled on the device.
private static final String REDIRECT_URI = "";
// OAuth2 client_id = APPID
private static final String CLIENT_ID = "";
String username;
String access_token;
String refresh_token;
private CountDownLatch latch;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
getDialog().setTitle("Sign in to ArcGIS Online");
final View root = inflater.inflate(R.layout.activity_main, null);
root.findViewById(R.id.progressbar).setVisibility(View.VISIBLE);
final WebView webView = (WebView) root.findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
final String code = url.substring(url.indexOf("?code=") + 6,
url.length());
AsyncTask.execute(new Runnable() {
@Override
public void run() {
try {
requestToken("https://www.arcgis.com/sharing/rest/oauth2/token?client_id="
+ CLIENT_ID
+ "&redirect_uri="
+ REDIRECT_URI
+ "&grant_type=authorization_code&code="
+ code);
} catch (Exception e) {
Log.e(getClass().getSimpleName(), "", e);
}
dismiss();
}
});
return true;
}
@Override
public void onPageFinished(WebView view, String url) {
webView.setVisibility(View.VISIBLE);
root.findViewById(R.id.progressbar).setVisibility(View.GONE);
}
});
webView.loadUrl("https://www.arcgis.com/sharing/oauth2/authorize?client_id="
+ CLIENT_ID
+ "&response_type=code&redirect_uri="
+ REDIRECT_URI);
return root;
}
@Override
public void onDismiss(DialogInterface dialog) {
if (latch != null)
latch.countDown();
super.onDismiss(dialog);
}
public void setLatch(CountDownLatch latch) {
this.latch = latch;
}
private void requestToken(String url) throws JsonParseException,
MalformedURLException, IOException {
JsonFactory f = new JsonFactory();
JsonParser json = f.createJsonParser(new URL(url));
json.nextToken();
while (json.nextToken() != JsonToken.END_OBJECT) {
String name = json.getCurrentName();
json.nextToken();
if ("username".equals(name))
username = json.getText();
else if ("access_token".equals(name))
access_token = json.getText();
else if ("refresh_token".equals(name))
refresh_token = json.getText();
Log.i(getClass().getSimpleName(), name + " = " + json.getText());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment