Search code examples
androidgmailoauth-2.0

How to Login into Gmail using OAuth in Android Application?


I am Developing an application which uses Login to Gmail.I gone through all tutorials,stackoverflow questions which is tagged under OAuth 2.0 and documents that are available in google and finally as per the guide lines given in official document of Google for OAuth 2.0 sample. I have created Client ID and everything that is required for installed applications i.e., for Android. Everything up to now works fine,and i called WebView to grant permission from the user,After that i got Accesstoken like 4/cR7XXXXXXXXXXXXXXX in the WebViewand saying something like Please copy this code,switch to your application and paste it here.I am confused here,i don't know what to do,to get back to my app from Webview .Am searching for the solution about two days but,Am not able to get good answer for my problem.Here is the code where i was got stoped.

Main.java where user have an OptionMenu to login. When the user clicks WebViewopens to enter gmail.

import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class Main extends Activity {
    public static String REQUEST = "https://accounts.google.com/o/oauth2/auth?"
            + "client_id=XXXXXXXXXXX-gxxxx.apps.googleusercontent.com&"
            + "redirect_uri=urn:ietf:wg:oauth:2.0:oob&"
            + "scope=https://mail.google.com/mail/feed/atom&"
            + "response_type=code&" + "access_type=online";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
        case 0:
            if (requestCode != RESULT_OK || data == null) {
                return;
            }
            String token = data.getStringExtra("token");
            if (token != null) {

            }
            return;
        }
        super.onActivityResult(requestCode, resultCode, data);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.item1:
            Intent intent_obj2 = new Intent(Main.this, Webview.class);
            intent_obj2.setData(Uri.parse(REQUEST));
            startActivityForResult(intent_obj2, 0);
            return true;
            }
        return super.onOptionsItemSelected(item);
    }
}

Webview.java

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.view.Window;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class Webview extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_PROGRESS);
        final WebView wb_obj = new WebView(this);
        setContentView(wb_obj);
        wb_obj.getSettings().setJavaScriptEnabled(true);
        Intent intent = getIntent();
        if (intent.getData() != null) {
            wb_obj.loadUrl(intent.getDataString());
        }

        wb_obj.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                setProgress(newProgress * 10000);
            }

        });
        wb_obj.setWebViewClient(new WebViewClient() {

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                setTitle(url);
                System.out.println(url);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                System.out.println("in onPageFinsihed");

                /*CookieSyncManager.getInstance().sync();
                String s_cookie = CookieManager.getInstance().getCookie(url);
                if (s_cookie == null) {
                    System.out.println(s_cookie);
                    return;
                }else{

                String web_title = wb_obj.getTitle().toString();
                System.out.println("web tile" + web_title);

                if (web_title.equalsIgnoreCase("Request for Permission")) {

                } else {

                    String[] s_webtitle = web_title.split("=", 2);
                    String access_token = s_webtitle[1].toString();
                    //System.out.println("Access token" + access_token);
                    startActivity(new Intent(Webview.this, Main.class));
                    finish();
                }*/
                }

        });

    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        startActivity(new Intent(Webview.this, Main.class));
    }
}

As per Webview.java i called finish() so that current activity gets killed but this is nit happening in this app,so that i will get token in onAcitivityResult().Please share Your answers thank you.


Solution

  • Below steps are require to login to Google.

    1- Select an account from your device using below code

    public static AccountManager accountManager;
    accountManager = AccountManager.get(this);
    Account[] accounts = accountManager.getAccountsByType("com.google");
    

    2- Get a Token from selected account using below code

    private void onAccountSelected(final Account account) {
    accountManager.getAuthToken(account, AUTH_TOKEN_TYPE, null, this, new AccountManagerCallback<Bundle>() {
    public void run(AccountManagerFuture<Bundle> future) {
        try {
            String token = future.getResult().getString(AccountManager.KEY_AUTHTOKEN);
            useToken(account, token);
        } catch (OperationCanceledException e) {
            onAccessDenied();
        } catch (Exception e) {
            handleException(e);
        }
    }
    }, null);
    
    }
    

    3- now Authenticate the Token using user account and Token. you will be able to login to google.

    NOTE: you will get Authentication full code from here Authentication code , put your gmail a/c and token where required. now you are able to loging using OAuth.

    4- for re login you have to invalidate your token using below code

    accountManager.invalidateAuthToken("com.google", token);
    

    5- after invalidate you have to get a new token using below code

     String newToken = AccountManager.get(this).getAuthToken(new Account(account,        "com.google"),
                 AUTH_TOKEN_TYPE, true, null, null).getResult().getString(AccountManager.KEY_AUTHTOKEN);
    

    6- in your AndroidManifest.xml add below uses permissions

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.GET_ACCOUNTS"/>
    <uses-permission android:name="android.permission.USE_CREDENTIALS"/>
    

    Thats all you require, now enjoy.