如何在 Android 应用程序中使用 OAuth 登录 Gmail? [英] How to Login into Gmail using OAuth in Android Application?

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

问题描述

我正在开发一个使用登录 Gmail 的应用程序.我浏览了所有教程、标记在 OAuth 2.0 下的 stackoverflow 问题和谷歌中可用的文档,最后按照给出的指南在 Google 的 OAuth 2.0 官方文档中 示例.我已经创建了客户端 ID 以及已安装的应用程序(即 Android)所需的一切.到目前为止一切正常,我调用 WebView 来授予用户权限,之后我得到了 Accesstoken 就像 4/cR7XXXXXXXXXXXXXXXWebView 并说类似请复制此代码,切换到您的应用程序并将其粘贴到此处.我在这里很困惑,我不知道该怎么做,要回来从 Webview 到我的应用程序.我正在寻找大约两天的解决方案,但是,我无法为我的问题找到好的答案.这是我被阻止的代码.

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,我调用了 finish() 以便当前活动被终止,但这在此应用程序中并未发生,因此我将在 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.

推荐答案

以下步骤需要登录 Google.

Below steps are require to login to Google.

1-使用以下代码从您的设备中选择一个帐户

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- 使用以下代码从所选帐户中获取令牌

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.

注意:您将从这里获得身份验证的完整代码 身份验证代码 ,将您的 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- 要重新登录,您必须使用以下代码使您的令牌无效

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

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

5- 无效后,您必须使用以下代码获取新令牌

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.

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

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