在Firebase项目中集成gmail连接

时间:2017-07-17 14:48:56

标签: android firebase gmail gmail-api google-developers-console

我开发了一个使用gmail api从用户那里获取所有邮件的应用程序。然后我将这个应用程序划分为一个样本(几乎为空)和一个完成所有操作的片段,以便稍后我可以轻松地将我的片段集成到我团队的项目设置中。

现在我的片段在另一个项目中,gmail连接不起作用并给我这些错误:

E/Async Task: com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAuthIOException
E/Google log in: failed

我认为这个错误是因为该项目使用了firebase并且已经有一个google-services.json文件,并且我没有使用它。 我们在google开发者门户网站中添加了GMail API,并生成了一个新的json文件,但它似乎无法正常工作。

为什么我的GMail连接失败了,我该如何解决?

2 个答案:

答案 0 :(得分:1)

好的,我设法让它发挥作用。

在我在API管理器Google控制台中创建凭据密钥时,它似乎没有在Firebase中的项目的所有应用中添加SHA1密钥。

所有我必须做的(经过一周的努力工作)是将SHA1从应用程序“链接”粘贴到另一个应用程序中的Google API控制台

我希望它可以提供帮助

答案 1 :(得分:0)

使用此代码使用firebase集成gmail登录。如果已经登录,它将导航到homeScreen,如果之前没有登录,一旦点击登录,它将弹出电子邮件登录。

在string.xml中添加server_client_id 在这里使用:

  

的getString(R.string.server_client_id)

代码:

  

MainActivity.java

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;
import smart.works.android.bharat.com.codeplay.ui.homeScreen.CodePlayActivity;
import smart.works.android.bharat.com.codeplay.R;
import smart.works.android.bharat.com.codeplay.Utils.AppConstants;
import smart.works.android.bharat.com.codeplay.Utils.PreferenceUtils;

public class MainActivity extends AppCompatActivity
    implements GoogleApiClient.OnConnectionFailedListener, View.OnClickListener {

  private static final int RC_SIGN_IN = 124;
  private static final String TAG = "MainActivity";
  private GoogleApiClient mGoogleApiClient;
  private FirebaseAuth mAuth;
  private ProgressBar mProgressBar;
  private SignInButton mSignInButton;

  @Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    initUi();
    setupUi();
  }

  private void setupUi() {
    GoogleSignInOptions gso =
        new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestIdToken(
            getString(R.string.server_client_id)).requestEmail().build();
    mGoogleApiClient =
        new GoogleApiClient.Builder(this).enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
            .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
            .build();
    // Set the dimensions of the sign-in button.
    mSignInButton = (SignInButton) findViewById(R.id.sign_in_button);
    mSignInButton.setSize(SignInButton.SIZE_STANDARD);
    findViewById(R.id.sign_in_button).setOnClickListener(this);
    mAuth = FirebaseAuth.getInstance();
  }

  private void initUi() {
    mProgressBar = (ProgressBar) findViewById(R.id.sign_in_progress);
    mSignInButton = (SignInButton) findViewById(R.id.sign_in_button);
  }

  @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

  }

  @Override public void onClick(View v) {
    switch (v.getId()) {
      case R.id.sign_in_button:
        signIn();
        break;
    }
  }

  private void signIn() {
    Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
    startActivityForResult(signInIntent, RC_SIGN_IN);
  }

  private void showProgress() {
    mProgressBar.setVisibility(View.VISIBLE);
    mSignInButton.setEnabled(false);
  }

  private void cancelProgress() {
    mProgressBar.setVisibility(View.GONE);
    mSignInButton.setEnabled(true);
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
    if (requestCode == RC_SIGN_IN) {
      showProgress();
      GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
      handleSignInResult(result);
    }
  }

  private void handleSignInResult(GoogleSignInResult result) {
    Log.d(TAG, "handleSignInResult:" + result.isSuccess());
    if (result.isSuccess()) {
      // Google Sign In was successful, authenticate with Firebase
      GoogleSignInAccount account = result.getSignInAccount();
      firebaseAuthWithGoogle(account);

      //updateUI(true);
    } else {
      cancelProgress();
      Toast.makeText(MainActivity.this, "sign in failed ! Try Again ", Toast.LENGTH_SHORT).show();
      // Signed out, show unauthenticated UI.
      //updateUI(false);
    }
  }

  @Override public void onStart() {
    super.onStart();
    // Check if user is signed in (non-null) and update UI accordingly.
    FirebaseUser currentUser = mAuth.getCurrentUser();
    if (currentUser != null) {
      forwardToHomeScreen(currentUser);
    }

    //updateUI(currentUser);

  }


  private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
    Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());

    AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
    mAuth.signInWithCredential(credential)
        .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
          @Override public void onComplete(@NonNull Task<AuthResult> task) {
            cancelProgress();
            if (task.isSuccessful()) {
              // Sign in success, update UI with the signed-in user's information
              Log.d(TAG, "signInWithCredential:success");
              FirebaseUser user = mAuth.getCurrentUser();
              forwardToHomeScreen(user);
            } else {
              // If sign in fails, display a message to the user.
              Log.w(TAG, "signInWithCredential:failure", task.getException());
              Toast.makeText(MainActivity.this, "Authentication failed.", Toast.LENGTH_SHORT)
                  .show();
              //updateUI(null);
            }

            // ...
          }
        });
  }

  private void forwardToHomeScreen(FirebaseUser user) {
    PreferenceUtils preferenceUtils = new PreferenceUtils(this);
    preferenceUtils.getPrefEditor().putString(AppConstants.USER_ID, user.getUid()).apply();
    Intent i = new Intent(this, CodePlayActivity.class);
    i.putExtra(AppConstants.USER_NAME, user.getDisplayName());
    i.putExtra(AppConstants.USER_EMAIL, user.getEmail());
    i.setData(user.getPhotoUrl());
    startActivity(i);
    finish();
  }
}
  

actvity_main.xml

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/nav_bg"
    android:orientation="vertical"
    >

  <ImageView
      android:id="@+id/icon"
      android:layout_width="100dp"
      android:layout_height="100dp"
      android:layout_alignParentTop="true"
      android:layout_centerInParent="true"
      android:layout_marginTop="100dp"
      android:contentDescription="@string/app_icon"
      android:src="@mipmap/ic_launcher"
      />
  <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_below="@+id/icon"
      android:layout_centerInParent="true"
      android:layout_marginBottom="60dp"
      android:text="@string/app_name"
      android:textColor="#FFFFFF"
      android:textSize="16sp"
      android:textStyle="bold"
      />
  <ProgressBar
      android:id="@+id/sign_in_progress"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"
      android:indeterminate="true"
      android:visibility="gone"
      />
  <com.google.android.gms.common.SignInButton
      android:id="@+id/sign_in_button"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignParentBottom="true"
      android:layout_centerInParent="true"
      android:layout_marginBottom="100dp"
      />


</RelativeLayout>