如何登录到Gmail的Andr​​oid应用程序使用OAuth? [英] How to Login into Gmail using OAuth in Android Application?

查看:149
本文介绍了如何登录到Gmail的Andr​​oid应用程序使用OAuth?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发,它使用登录Gmail.I通过所有的教程,计算器问题,这是根据标记的OAuth 2.0 以及可在谷歌文档和终于走了一个应用程序按照在谷歌的官方文档的OAuth 2.0 <特定的引导线href="https://sites.google.com/site/oauthgoog/oauth-practices/mobile-apps-for-complex-login-systems/sample$c$c"相对=nofollow>样本。我创建所需的安装的应用程序,即,为Android客户端ID和一切。一切到现在工作得很好,我叫的WebView 从用户授予权限,在那之后我得到 Accesstoken 4 / cR7XXXXXXXXXXXXXXX 的WebView ,说像请复制此code,切换到您的应用程序并将其贴在这里。我很困惑在这里,我不知道该怎么办,要回我的应用程序从 web视图 .AM寻找两天的解决方案,但是,我不能够得到很好的回答了我的problem.Here是code我在那里得到了采空。

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 ,其中用户有一个 OptionMenu 登录。当用户点击的WebView 打开进入Gmail中。

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

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));
    }
}

根据Webview.java我叫完成(),这样当前的活动就会被杀死,但这是NIT发生在这个应用程序,这样我会得到令牌的 onAcitivityResult()。请分享你的答案,谢谢你。

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.

推荐答案

以下步骤需要登录到谷歌。

Below steps are require to login to Google.

1 - 使用下面code。选择从设备的帐户

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 - 从选择的帐户使用下面code获得令牌

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 - 现在正在使用的用户帐户和令牌身份验证令牌。您将能够登录到谷歌。

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

注意:您将得到充分验证code从这里的验证code ,把你的Gmail A / C和在需要令牌。现在你可以使用OAuth登录电子。

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 - 重新登录您在使用低于code无效令牌

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

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

5 - 无效后,你必须使用以下code以获得一个新的令牌

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 - 在AndroidManifest.xml中下方添加使用权限

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.

这篇关于如何登录到Gmail的Andr​​oid应用程序使用OAuth?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆