Так что, как следует из названия, я пытаюсь добавить вход в Google (firebase auth) в мое приложение.
У меня есть код ниже (извините за беспорядок!), И что происходит, это позволяет мне добавить нового пользователя, когда я нажимаю на кнопку Google, но затем, когда я нажимаю на учетную запись Google, чтобывойти с помощью этого просто возвращает меня на страницу входа.Я попытался добавить новое намерение, чтобы перенести меня в UserMainPage, но это не сработало.Мне было интересно, были ли какие-либо явные ошибки в моем коде?
У меня есть 3 действия:
LoginActivity
RegistrationActivity
UserMainActivity
Код ниже от входа в систему
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.ApiException;
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;
public class LoginActvity extends AppCompatActivity {
private FirebaseAuth mAuth;
private EditText emailText, passwordText;
private Button normalSignInButton;
private static final int RC_SIGN_IN = 9001;
private SignInButton button;
private GoogleSignInClient mGoogleSignInClient;
private static final String TAG = "GoogleActivity";
FirebaseAuth.AuthStateListener mAuthListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_actvity);
emailText = findViewById(R.id.log_email);
passwordText = findViewById(R.id.log_password);
normalSignInButton = findViewById(R.id.log_sign_in_button);
mAuth = FirebaseAuth.getInstance();
button = (SignInButton) findViewById(R.id.googleBtn);
mAuthListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
if (firebaseAuth.getCurrentUser() != null){
startActivity(new Intent(LoginActvity.this, UserMainActivity.class));
}
}
};
normalSignInButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String email = emailText.getText().toString();
String password = passwordText.getText().toString();
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(LoginActvity.this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(LoginActvity.this, "Authentication SUCCESS.",
Toast.LENGTH_SHORT).show();
// Sign in success, update UI with the signed-in user's information
// Log.d(TAG, "signInWithEmail:success");
FirebaseUser user = mAuth.getCurrentUser();
//updateUI(user);
startActivity(new Intent(LoginActvity.this, UserMainActivity.class));
} else {
// If sign in fails, display a message to the user.
// Log.w(TAG, "signInWithEmail:failure", task.getException());
Toast.makeText(LoginActvity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
//updateUI(null);
}
// ...
}
});
}
});
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
signIn();
}
});
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
mAuth = FirebaseAuth.getInstance();
}
@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) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
// Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = task.getResult(ApiException.class);
firebaseAuthWithGoogle(account);
} catch (ApiException e) {
// Google Sign In failed, update UI appropriately
Log.w(TAG, "Google sign in failed", e);
// ...
}
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success");
FirebaseUser user = mAuth.getCurrentUser();
startActivity(new Intent(LoginActvity.this, UserMainActivity.class));
//updateUI(user);
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
// Snackbar.make(findViewById(R.id.log_Create_new_account), "Authentication Failed.", Snackbar.LENGTH_SHORT).show();
//updateUI(null);
}
}
});
}
protected void onStart(){
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
public void onClick(View v) {
startActivity(new Intent(LoginActvity.this, SignupActivity.class));
}
}
Код ниже от UserMainActivity:
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class UserMainActivity extends AppCompatActivity {
private TextView userEmail;
private Button signOut;
FirebaseAuth mAuth;
FirebaseAuth.AuthStateListener mAuthListener;
protected void onStart(){
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_main);
signOut = findViewById(R.id.sign_out_button);
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
if (firebaseAuth.getCurrentUser() == null){
startActivity(new Intent(UserMainActivity.this, LoginActvity.class));
}
}
};
signOut.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mAuth.signOut();
}
});
userEmail = findViewById(R.id.userEmailTV);
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
// Name, email address, and profile photo Url
String name = user.getDisplayName();
String email = user.getEmail();
//Uri photoUrl = user.getPhotoUrl();
// Check if user's email is verified
boolean emailVerified = user.isEmailVerified();
// The user's ID, unique to the Firebase project. Do NOT use this value to
// authenticate with your backend server, if you have one. Use
// FirebaseUser.getToken() instead.
String uid = user.getUid();
userEmail.setText(email);
}
}
}
Спасибо всем!