Я полагаю, что вы уже добавили Firebase в свой проект, если нет, перейдите по этой ссылке https://firebase.google.com/docs/auth/android/google-signin
Затем вам нужно включить google-вход в Firebase, выбрав Аутентификация на левой панели, затем выберите входвкладка провайдера и включите вход в Google.
сценарий сборки вашего уровня проекта должен выглядеть следующим образом
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.4.1'
classpath 'com.google.gms:google-services:4.2.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
И файл build.gradle уровня приложения должен иметь эти зависимости
//firebasecore
implementation 'com.google.firebase:firebase-core:17.0.0'
//firebase auth
implementation 'com.google.firebase:firebase-auth:18.0.0'
//google auth
implementation 'com.google.android.gms:play-services-auth:17.0.0'
и логин должен иметь такой код
public class Login_Activity extends AppCompatActivity {
ImageView gLogin;
private static final int RC_SIGN_IN=1;
private FirebaseAuth mAuth;
GoogleSignInClient mGoogleSignInClient;
Firebase user;
@Override
protected void onStart() {
super.onStart();
user = mAuth.getCurrentUser();
if(user!=null)
{
startActivity(new Intent(Login_Activity.this,MainActivity.class));
Login_Activity.this.finish();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_);
gLogin=findViewById(R.id.gLogin);
// ...
// Initialize Firebase Auth
mAuth = FirebaseAuth.getInstance();
// Configure sign-in to request the user's ID, email address, and basic
// profile. ID and basic profile are included in DEFAULT_SIGN_IN.
GoogleSignInOptions gso = new
GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
// Build a GoogleSignInClient with the options specified by gso.
mGoogleSignInClient= GoogleSignIn.getClient(this, gso);
gLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
signIn();
}
});
}
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
Toast.makeText(this, "starting activity", Toast.LENGTH_SHORT).show();
}
@Override
public void onActivityResult(int requestCode, int resultCode,Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from
GoogleSignInClient.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
// The Task returned from this call is always completed, no need to
//attach
// a listener.
Task<GoogleSignInAccount> task =
GoogleSignIn.getSignedInAccountFromIntent(data);
Toast.makeText(this, "inside on Activity result",
Toast.LENGTH_SHORT).show();
try {
Toast.makeText(this, "authenticating", Toast.LENGTH_SHORT).show();
// 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("firebase exception", "Google sign in failed", e);
// ...
}
//handleSignInResult(task);
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
Log.d("authenticate", "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)
{
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d("message","signInWithCredential:success");
user = mAuth.getCurrentUser();
Log.d("user id", user.getUid());
startActivity(new
Intent(Login_Activity.this,MainActivity.class));
Login_Activity.this.finish();
} else {
// If sign in fails, display a message to the user.
Log.w("message","signInWithCredential:failure", task.getException());
}
}
});
}
вам необходимо запросить токен с google sign. В опциях, которые вы можете использовать этот код, он будет регистрировать вас с помощью логина google с записями в базе данных аутентифицированных пользователей firebase.
Для базы данных вы должны один раз проверить правила базы данных для разрешения на чтение для чтения, и это должно работать