android - 如何从我的 Android 应用程序访问新的 Gmail API?

标签 android oauth-2.0 google-plus google-oauth gmail-api

我正在尝试访问新的 Gmail API (宣布 25.06.2014)从我的 Android 应用程序返回某个用户帐户中的所有电子邮件。我正在使用 ADT 插件在 Eclipse 中开发应用程序。
到目前为止我做了什么:

  • 我在 Google Developers Console 中注册了应用程序
    (链接:console.developers.google.com/project)。

  • 我已经实现了 Google+ 登录按钮(链接:developers.google.com/+/mobile/android/sign-in)。 Google+ 登录按钮可对用户进行身份验证并管理 OAuth 2.0 流程,从而简化您与 Google API 的集成。

  • 我将附加范围“https://www.googleapis.com/auth/gmail.readonly”添加到 Google+ 授权中,用于访问 Gmail API,如
    (链接:< strong>developers.google.com/gmail/api/v1/reference/users/threads/list)。

此时我有一个初始化的 GoogleApiClient 对象。

GoogleApiClient 对象将 ServiceConnection(链接:developer.android.com/reference/android/content/ServiceConnection.html)包装到 Google Play 服务。 GoogleApiClient 对象用于与 Google+ API 进行通信,并在与服务建立异步连接后生效,表明:

  • 设备上正在运行 Google Play 服务,并且应用 Activity 已成功绑定(bind)服务连接,
  • 用户选择了他们希望在应用中使用的帐户,并且
  • 用户的帐户已授予应用请求的权限。



我如何从这里着手获取所有带有此 httprequest 的消息?
此时我尝试访问Gmail API,但收到身份验证错误401:需要登录,即使Google+登录成功,我也成功返回了用户圈子列表。

编辑:SecondActivity.java

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

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;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.CommonStatusCodes;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Scope;
import com.google.android.gms.plus.People;
import com.google.android.gms.plus.People.LoadPeopleResult;
import com.google.android.gms.plus.Plus;
import com.google.android.gms.plus.model.people.Person;
import com.google.android.gms.plus.model.people.PersonBuffer;
import com.google.api.services.gmail.Gmail;
import com.google.api.services.gmail.Gmail.Users;
import com.google.api.services.gmail.Gmail.Users.Messages.GmailImport;
import com.google.api.services.gmail.GmailRequest;
import com.google.api.services.gmail.GmailRequestInitializer;
import com.google.api.services.gmail.GmailScopes;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.PendingIntent;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import mk.ukim.feit.recognizer.application.PeopleAdapter;
import mk.ukim.feit.recognizer.interfaces.GetMessages;
import mk.ukim.feit.recognizer.tasks.GetMessagesTask;
import mk.ukim.feit.recognizer.util.MyClass;
import mk.ukim.feit.recognizer.util.exception.FaceClientException;
import mk.ukim.feit.recognizer.util.model.Face;
import mk.ukim.feit.recognizer.util.model.Guess;
import mk.ukim.feit.recognizer.util.model.Photo;
import mk.ukim.feit.recognizer.util.response.PhotoResponse;
import mk.ukim.feit.recognizer.util.response.PhotoResponseImpl;

import java.io.IOException;
import java.util.ArrayList;


public class SecondActivity extends FragmentActivity implements
    GetMessages, ConnectionCallbacks, OnConnectionFailedListener,
    ResultCallback<People.LoadPeopleResult>, View.OnClickListener {

  private static final String TAG = "android-plus-quickstart";

  private static final int STATE_DEFAULT = 0;
  private static final int STATE_SIGN_IN = 1;
  private static final int STATE_IN_PROGRESS = 2;

  private static final int RC_SIGN_IN = 0;
  private static final int MY_ACTIVITYS_AUTH_REQUEST_CODE=045;

  private static final int DIALOG_PLAY_SERVICES_ERROR = 0;

  private static final String SAVED_PROGRESS = "sign_in_progress";

  private GoogleApiClient mGoogleApiClient;
  String name; 

  private PendingIntent mSignInIntent;
  private int mSignInError;
  private SignInButton mSignInButton;
  private Button mSignOutButton;
  private Button mRevokeButton;
  private TextView mStatus;
  private ListView mCirclesListView;
  private ArrayAdapter<String> mCirclesAdapter;
  private ArrayList<String> mCirclesList;

  public Scope gmail=new Scope("https://www.googleapis.com/auth/gmail.readonly");
  String scope="https://www.googleapis.com/auth/gmail.readonly";
  String email="email@gmail.com";



@Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_second);

    Intent intent = getIntent();
    name="Team";

    mSignInButton = (SignInButton) findViewById(R.id.sign_in_button);
    mSignOutButton = (Button) findViewById(R.id.sign_out_button);
    mRevokeButton = (Button) findViewById(R.id.revoke_access_button);
    mStatus = (TextView) findViewById(R.id.sign_in_status);
    mCirclesListView = (ListView) findViewById(R.id.circles_list);

    mSignInButton.setOnClickListener(this);
    mSignOutButton.setOnClickListener(this);
    mRevokeButton.setOnClickListener(this);

    mCirclesList = new ArrayList<String>();
    mCirclesAdapter = new ArrayAdapter<String>(
        this, R.layout.circle_member, mCirclesList);
    mCirclesListView.setAdapter(mCirclesAdapter);

    if (savedInstanceState != null) {
      mSignInProgress = savedInstanceState
          .getInt(SAVED_PROGRESS, STATE_DEFAULT);

    }

    mGoogleApiClient = buildGoogleApiClient();
  }



private GoogleApiClient buildGoogleApiClient() {
    return new GoogleApiClient.Builder(this)
        .addConnectionCallbacks(this)
        .addOnConnectionFailedListener(this)
        .addApi(Plus.API, Plus.PlusOptions.builder().build())
        .addScope(Plus.SCOPE_PLUS_LOGIN)
        .addScope(gmail)
        .build();
  }

@Override
  protected void onStart() {
    super.onStart();
    mGoogleApiClient.connect();
    getAndUseAuthTokenInAsyncTask();
  }



@Override
  protected void onStop() {
    super.onStop();

    if (mGoogleApiClient.isConnected()) {
      mGoogleApiClient.disconnect();
    }
  }

  @Override
  protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt(SAVED_PROGRESS, mSignInProgress);
  }



@Override
  public void onClick(View v) {
    if (!mGoogleApiClient.isConnecting()) {
          switch (v.getId()) {
          case R.id.sign_in_button:
            mStatus.setText(R.string.status_signing_in);
            resolveSignInError();
            break;
          case R.id.sign_out_button:
            Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
            mGoogleApiClient.disconnect();
            mGoogleApiClient.connect();
            break;
          case R.id.revoke_access_button:
            Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
            Plus.AccountApi.revokeAccessAndDisconnect(mGoogleApiClient);
            mGoogleApiClient = buildGoogleApiClient();
            mGoogleApiClient.connect();
            break;
      }
    }
  }

  @Override
  public void onConnected(Bundle connectionHint) {
    Log.i(TAG, "onConnected");

    getAndUseAuthTokenInAsyncTask();

    mSignInButton.setEnabled(false);
    mSignOutButton.setEnabled(true);
    mRevokeButton.setEnabled(true);

    // Retrieve some profile information. This is OK
    Person currentUser = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
    String klient=mGoogleApiClient.toString();


    mStatus.setText(String.format(
        getResources().getString(R.string.signed_in_as),
        currentUser.getDisplayName()));


    Plus.PeopleApi.loadVisible(mGoogleApiClient, null)
        .setResultCallback(this);

    GetMessagesTask task = new GetMessagesTask(
            SecondActivity.this, name, mGoogleApiClient);
        task.setDelegate(SecondActivity.this);
        task.execute();

    // Indicate that the sign in process is complete.
    mSignInProgress = STATE_DEFAULT;

  }

  @Override
  public void onConnectionFailed(ConnectionResult result) {
    // Refer to the javadoc for ConnectionResult to see what error codes might
    // be returned in onConnectionFailed.
    Log.i(TAG, "onConnectionFailed: ConnectionResult.getErrorCode() = "
        + result.getErrorCode());

    if (mSignInProgress != STATE_IN_PROGRESS) {
      mSignInIntent = result.getResolution();
      mSignInError = result.getErrorCode();

      if (mSignInProgress == STATE_SIGN_IN) {
        // STATE_SIGN_IN indicates the user already clicked the sign in button
        // so we should continue processing errors until the user is signed in
        // or they click cancel.
        resolveSignInError();
      }
    }

    onSignedOut();
  }


  private void resolveSignInError() {
    if (mSignInIntent != null) {

      try {
        mSignInProgress = STATE_IN_PROGRESS;
        startIntentSenderForResult(mSignInIntent.getIntentSender(),
            RC_SIGN_IN, null, 0, 0, 0);
      } catch (SendIntentException e) {
        Log.i(TAG, "Sign in intent could not be sent: "
            + e.getLocalizedMessage());
        // The intent was canceled before it was sent.  Attempt to connect to
        // get an updated ConnectionResult.
        mSignInProgress = STATE_SIGN_IN;
        mGoogleApiClient.connect();

      }
    } else {
      // Google Play services wasn't able to provide an intent for some
      // error types, so we show the default Google Play services error
      // dialog which may still start an intent if the
      // user can resolve the issue.
      showDialog(DIALOG_PLAY_SERVICES_ERROR);
    }
  }


  @Override
  public void onResult(LoadPeopleResult peopleData) {
    if (peopleData.getStatus().getStatusCode() == CommonStatusCodes.SUCCESS) {
      mCirclesList.clear();
      PersonBuffer personBuffer = peopleData.getPersonBuffer();
      try {
          int count = personBuffer.getCount();
          for (int i = 0; i < count; i++) {
              mCirclesList.add(personBuffer.get(i).getDisplayName());
          }
      } finally {
          personBuffer.close();
      }

      mCirclesAdapter.notifyDataSetChanged();
    } else {
      Log.e(TAG, "Error requesting visible circles: " + peopleData.getStatus());
    }
  }

  private void onSignedOut() {
    // Update the UI to reflect that the user is signed out.
    mSignInButton.setEnabled(true);
    mSignOutButton.setEnabled(false);
    mRevokeButton.setEnabled(false);

    mStatus.setText(R.string.status_signed_out);

    mCirclesList.clear();
    mCirclesAdapter.notifyDataSetChanged();
  }

  @Override
  public void onConnectionSuspended(int cause) {
    // The connection to Google Play services was lost for some reason.
    // We call connect() to attempt to re-establish the connection or get a
    // ConnectionResult that we can attempt to resolve.
    mGoogleApiClient.connect();
  }

  @Override
  protected Dialog onCreateDialog(int id) {
    switch(id) {
      case DIALOG_PLAY_SERVICES_ERROR:
        if (GooglePlayServicesUtil.isUserRecoverableError(mSignInError)) {
          return GooglePlayServicesUtil.getErrorDialog(
              mSignInError,
              this,
              RC_SIGN_IN,
              new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                  Log.e(TAG, "Google Play services resolution cancelled");
                  mSignInProgress = STATE_DEFAULT;
                  mStatus.setText(R.string.status_signed_out);
                }
              });
        } else {
          return new AlertDialog.Builder(this)
              .setMessage(R.string.play_services_error)
              .setPositiveButton(R.string.close,
                  new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                      Log.e(TAG, "Google Play services error could not be "
                          + "resolved: " + mSignInError);
                      mSignInProgress = STATE_DEFAULT;
                      mStatus.setText(R.string.status_signed_out);
                    }
                  }).create();
        }
      default:
        return super.onCreateDialog(id);
    }
  }




    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
           if (requestCode == MY_ACTIVITYS_AUTH_REQUEST_CODE) {
               if (resultCode == RESULT_OK) {
                   getAndUseAuthTokenInAsyncTask();
               }
           }
       }


       public void getAndUseAuthTokenBlocking() throws UserRecoverableAuthException, IOException, GoogleAuthException {

              final String token = GoogleAuthUtil.getToken(this, email, scope);
              String fff="";
        }      


       public void getAndUseAuthTokenInAsyncTask() {

        AsyncTask<Void, Void, Void> task = new AsyncTask<Void,Void, Void>() {


               @Override
               protected Void doInBackground(Void... params) {
                   // TODO Auto-generated method stub
                   try {
                    getAndUseAuthTokenBlocking();
                } catch (UserRecoverableAuthException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (GoogleAuthException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                   return null;
               }
           };
           task.execute((Void)null);
       }

    }

编辑 2:LogCat

07-16 06:44:27.300: E/AndroidRuntime(11875): FATAL EXCEPTION: AsyncTask #2
07-16 06:44:27.300: E/AndroidRuntime(11875): java.lang.RuntimeException: An error occured while executing doInBackground()
07-16 06:44:27.300: E/AndroidRuntime(11875):    at android.os.AsyncTask$3.done(AsyncTask.java:299)
07-16 06:44:27.300: E/AndroidRuntime(11875):    at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
07-16 06:44:27.300: E/AndroidRuntime(11875):    at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
07-16 06:44:27.300: E/AndroidRuntime(11875):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
07-16 06:44:27.300: E/AndroidRuntime(11875):    at java.util.concurrent.FutureTask.run(FutureTask.java:137)
07-16 06:44:27.300: E/AndroidRuntime(11875):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
07-16 06:44:27.300: E/AndroidRuntime(11875):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
07-16 06:44:27.300: E/AndroidRuntime(11875):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
07-16 06:44:27.300: E/AndroidRuntime(11875):    at java.lang.Thread.run(Thread.java:856)
07-16 06:44:27.300: E/AndroidRuntime(11875): Caused by: java.lang.NoClassDefFoundError: com.google.api.client.googleapis.auth.oauth2.GoogleCredential
07-16 06:44:27.300: E/AndroidRuntime(11875):    at mk.ukim.feit.recognizer.GmailLinkGrabberService$getAuthToken.doInBackground(GmailLinkGrabberService.java:104)
07-16 06:44:27.300: E/AndroidRuntime(11875):    at mk.ukim.feit.recognizer.GmailLinkGrabberService$getAuthToken.doInBackground(GmailLinkGrabberService.java:1)
07-16 06:44:27.300: E/AndroidRuntime(11875):    at android.os.AsyncTask$2.call(AsyncTask.java:287)
07-16 06:44:27.300: E/AndroidRuntime(11875):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
07-16 06:44:27.300: E/AndroidRuntime(11875):    ... 5 more

最佳答案

(2017 年 2 月) Gmail API (v1 launched 2014 年 6 月)是将 Gmail 功能集成到您的应用程序的最佳方式(并且优于 POP/IMAP 和 SMTP)。为了在 Android 中使用此 API 和大多数其他 Google API,您需要获取 the Google APIs Client Library for Android (或者对于更通用的 Java,the Google APIs Client Library for Java )。

现在是一些工作示例:这里是 Android quickstart &更一般的Java quickstart .拥有Gmail API JavaDocs reference在你身边也不是一个坏主意。 OAuth2 现在是执行身份验证的首选方式,这意味着您将需要看起来像这样的代码,加上正确的 scope :

// Sheets RO scope
private static final String[] SCOPES = {GmailScopes.GMAIL_READONLY};
    :

// Initialize credentials and service object
mCredential = GoogleAccountCredential.usingOAuth2(
        getApplicationContext(), Arrays.asList(SCOPES))
        .setBackOff(new ExponentialBackOff());

除了这个“设置”之外,OP 拥有让某些东西正常工作所需的大部分东西:

  1. developers console 中有一个项目& 使用 SHA1 哈希启用 Gmail API(如上文 Android 快速入门中所述)
  2. 使用正确的范围实现 OAuth2
  3. 制作 the callListThreadsResponse listResponse = mService.users().threads().list(user).execute(); - 快速入门使用 labels() 所以你可以改变到 threads()

要了解有关 API 的更多信息,以下是 3 个视频,是 API 发布时的第一个介绍。如果您对 Python 没有“过敏”,我使用 Gmail API 制作了另一对简短但更“真实”的示例(虽然非移动设备):

标题中没有提到它,但上面的第二个视频包含一个使用 Gmail API 访问线程和消息的代码示例。

关于android - 如何从我的 Android 应用程序访问新的 Gmail API?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24686631/

相关文章:

android - 撰写水平寻呼机总是填充最大尺寸,verticalAligment 不起作用

asp.net - ADFS 4.0 : Received invalid Client credentials

android - 如何在 Java 中单击按钮时在我的 Android 应用程序中注销 Google 用户?

javascript - 鉴于 "social sharing"徽章 ("Like"按钮等的流行,您如何降低与第三方 Javascript 相关的风险?

javascript - Google Share 按钮动态设置数据预填充文本

java - 什么是更好的: detecting device using its size or user agent string?

java - 以编程方式获取 ScrollView 的子级

android - 应该如何在 PagerAdapter 中使用 getApplication 方法

python - 需要让 OAuth 'flow' 在 Python 上的 Google Drive 上流动,以实现独立的 py 应用程序

android - 如何在Android中的自己的按钮上实现google plus登录功能