谷歌使用Firebase Android登录

谷歌使用Firebase Android登录,android,firebase,firebase-authentication,google-signin,Android,Firebase,Firebase Authentication,Google Signin,我尝试使用firebase实现Google登录。我浏览了文档并观看了一些视频,但没有一个有效。每当我点击谷歌登录按钮,什么都不会发生。同样,在成功登录后,我希望它引导到主要活动。我的应用程序从登录活动启动 public class SignIn extends AppCompatActivity { private FirebaseAuth mAuth; private FirebaseAuth.AuthStateListener mAuthListener; private static f

我尝试使用firebase实现Google登录。我浏览了文档并观看了一些视频,但没有一个有效。每当我点击谷歌登录按钮,什么都不会发生。同样,在成功登录后,我希望它引导到主要活动。我的应用程序从登录活动启动

public class SignIn extends AppCompatActivity {

private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private static final String TAG = "SignInActivity";
private static final int RC_SIGN_IN = 9001;
GoogleApiClient mGoogleApiClient;
private static Button googleSignIn;

@Override
protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_sign_in);

   // Configure Google Sign In
   GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
           .requestIdToken(getString(R.string.default_web_client_id))
           .requestEmail()
           .build();
   mAuth = FirebaseAuth.getInstance();
   mAuthListener = new FirebaseAuth.AuthStateListener() {
       @Override
       public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
           FirebaseUser user = firebaseAuth.getCurrentUser();
           if (user != null) {
               // User is signed in
               Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
           } else {
               // User is signed out
               Log.d(TAG, "onAuthStateChanged:signed_out");
           }
           // ...
       }
   };
   // ...

}

 @Override
 public void onStart() {
   super.onStart();
   mAuth.addAuthStateListener(mAuthListener);
 }

  @Override
  public void onStop() {
   super.onStop();
   if (mAuthListener != null) {
       mAuth.removeAuthStateListener(mAuthListener);
   }
 }

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

 @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) {
       GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
       if (result.isSuccess()) {
           // Google Sign In was successful, authenticate with Firebase
           GoogleSignInAccount account = result.getSignInAccount();
           firebaseAuthWithGoogle(account);
       } else {
           // Google Sign In failed, update UI appropriately
           // ...
       }
   }
  }

  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) {
                   Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful());

                   // If sign in fails, display a message to the user. If sign in succeeds
                   // the auth state listener will be notified and logic to handle the
                   // signed in user can be handled in the listener.
                   if (!task.isSuccessful()) {
                       Log.w(TAG, "signInWithCredential", task.getException());
                       Toast.makeText(SignIn.this, "Authentication failed.",
                               Toast.LENGTH_SHORT).show();
                   }
                   // ...
               }
           });
    }
    }
这是我的代码:

 protected void signInwithGoogle(){
    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestIdToken(getString(R.string.default_web_client_id))
            .requestEmail()
            .build();


    mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
            .enableAutoManage(getActivity(), this)
            .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
            .build();
    Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
    startActivityForResult(signInIntent, RC_SIGN_IN);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == RC_SIGN_IN) {
        GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
        if (result.isSuccess()) {
            GoogleSignInAccount acct = result.getSignInAccount();
            //TO USE
            String personName = acct.getDisplayName();
            String personEmail = acct.getEmail();
            String personId = acct.getId();
            Uri personPhoto = acct.getPhotoUrl();
            String personPhoneURL = acct.getPhotoUrl().toString();
 //                User user = new User();
 //                user.setUsername(personName);
 //                user.setEmail(personEmail);
//                user.setPersonId(personId);
//                user.setPersonProfileUrl(personPhoneURL);
//                user.setSignedInWithGoogle(true);

           // updateFirebaseData(user,personEmail);

            Gson gson = new GsonBuilder()
                    .registerTypeAdapter(Uri.class, new UriSerializer())
                    .create();

//                String userData = gson.toJson(user);
//                      EPreferenceManager.getSingleton().setUserdata(getActivity(),userData);
            firebaseAuthWithGoogle(acct);
        } else {
            Toast.makeText(getActivity(),"There was a trouble signing in-Please try again",Toast.LENGTH_SHORT).show();;
        }
    }
}


private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
    auth = FirebaseAuth.getInstance();
    AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
    auth.signInWithCredential(credential)
            .addOnCompleteListener(getActivity(), new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {

                    // If sign in fails, display a message to the user. If sign in succeeds
                    // the auth state listener will be notified and logic to handle the
                    // signed in user can be handled in the listener.
                    if (!task.isSuccessful()) {
                        Toast.makeText(getActivity(), "Authentication failed.",
                                Toast.LENGTH_SHORT).show();
                    }else{
                        Toast.makeText(getActivity(), "Authentication pass.",
                                Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(getActivity(), HomePageActivity.class);
                        startActivity(intent);
                        getActivity().finish();
                    }
                }
            });
}
protectedvoid-signiWithGoogle(){
GoogleSignenOptions gso=新建GoogleSignenOptions.Builder(GoogleSignenOptions.DEFAULT\u登录)
.requestIdToken(getString(R.string.default\u web\u client\u id))
.requestEmail()
.build();
mgoogleapclient=新的Googleapclient.Builder(getActivity())
.enableAutoManage(getActivity(),this)
.addApi(Auth.GOOGLE\u SIGN\u IN\u API,gso)
.build();
意向符号=Auth.googlesignianpi.getsignient(mgoogleapclient);
startActivityForResult(签名、注册);
}
@凌驾
ActivityResult上的公共void(int请求代码、int结果代码、意图数据){
super.onActivityResult(请求代码、结果代码、数据);
if(requestCode==RC\u登录){
GoogleSignInResult结果=Auth.GoogleSignInApi.getSignInResultFromIntent(数据);
if(result.issucess()){
GoogleSignInAccount acct=result.getSignInAccount();
//使用
字符串personName=acct.getDisplayName();
字符串personEmail=acct.getEmail();
字符串personId=acct.getId();
Uri personPhoto=acct.getPhotoUrl();
字符串personPhoneURL=acct.getPhotoUrl().toString();
//用户=新用户();
//user.setUsername(personName);
//user.setEmail(personEmail);
//user.setPersonId(personId);
//user.setPersonProfileUrl(personPhoneURL);
//user.setSignedwithGoogle(true);
//UPDATEFIA(用户、个人邮件);
Gson Gson=new GsonBuilder()
.registerTypeAdapter(Uri.class,新的UriSerializer())
.create();
//字符串userData=gson.toJson(用户);
//EPreferenceManager.getSingleton().setUserdata(getActivity(),userData);
firebaseAuthWithGoogle(acct);
}否则{
Toast.makeText(getActivity(),“登录时遇到问题,请重试”,Toast.LENGTH_SHORT.show();;
}
}
}
私有void firebaseAuthWithGoogle(谷歌签名帐户){
auth=FirebaseAuth.getInstance();
AuthCredential credential=GoogleAuthProvider.getCredential(acct.getIdToken(),null);
使用凭证(凭证)进行身份验证登录
.addOnCompleteListener(getActivity(),new OnCompleteListener()){
@凌驾
未完成的公共void(@NonNull任务){
//如果登录失败,则向用户显示消息。如果登录成功
//将通知身份验证状态侦听器,并使用逻辑来处理
//可以在侦听器中处理已登录用户。
如果(!task.issusccessful()){
Toast.makeText(getActivity(),“身份验证失败”,
吐司。长度(短)。show();
}否则{
Toast.makeText(getActivity(),“身份验证通过”,
吐司。长度(短)。show();
Intent Intent=新的Intent(getActivity(),HomePageActivity.class);
星触觉(意向);
getActivity().finish();
}
}
});
}

本手册提供了分步指导

添加这些依赖项:

compile 'com.google.firebase:firebase-core:9.0.0'
compile 'com.google.firebase:firebase-messaging:9.0.0'
compile 'com.google.firebase:firebase-auth:9.0.0'
compile 'com.github.bumptech.glide:glide:3.5.2'

// Google Sign In SDK (only required for Google Sign In)
compile 'com.google.android.gms:play-services-auth:9.0.0'
活动\u main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:orientation="vertical">


        <ImageView
            android:layout_width="150dp"
            android:id="@+id/iv_image"
            android:src="@drawable/profileimage"
            android:layout_gravity="center"
            android:layout_height="150dp" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_marginTop="5dp"
            android:layout_height="40dp">

            <TextView
                android:layout_width="100dp"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:layout_marginLeft="10dp"
                android:text="Name"
                android:textColor="#000000"
                android:textSize="15dp" />


            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:layout_marginLeft="10dp"
                android:text="Name"
                android:id="@+id/tv_name"
                android:textColor="#000000"
                android:textSize="15dp" />

        </LinearLayout>

        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="#000000"></View>


        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="40dp">

            <TextView
                android:layout_width="100dp"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:layout_marginLeft="10dp"
                android:text="Email"
                android:textColor="#000000"
                android:textSize="15dp" />


            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:layout_marginLeft="10dp"
                android:text="Email"
                android:id="@+id/tv_email"
                android:textColor="#000000"
                android:textSize="15dp" />

        </LinearLayout>

        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="#000000"></View>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_alignParentBottom="true"
        android:layout_margin="10dp"
        android:background="#E02F2F"
        android:orientation="horizontal">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/iv_google"
            android:src="@drawable/google_plus" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center"
            android:id="@+id/tv_google"
            android:gravity="center_vertical"
            android:text="Sign in with Google"
            android:textColor="#FFFFFF"
            android:textSize="20dp" />

    </LinearLayout>
</RelativeLayout>

MainActivity.java

package com.deepshikha.googlepluslogin;

import android.app.ProgressDialog;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
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.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
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 MainActivity extends AppCompatActivity implements View.OnClickListener, GoogleApiClient.OnConnectionFailedListener {

    private static final int RC_SIGN_IN = 9001;
    private FirebaseAuth mAuth;
    private FirebaseAuth.AuthStateListener mAuthListener;
    private GoogleApiClient mGoogleApiClient;
    ImageView iv_google;
    ProgressDialog dialog;
    ImageView iv_image;

    boolean boolean_google;
    TextView tv_name, tv_email, tv_google;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        init();
        listener();

    }

    private void init() {

        tv_name = (TextView) findViewById(R.id.tv_name);
        tv_email = (TextView) findViewById(R.id.tv_email);
        tv_google = (TextView) findViewById(R.id.tv_google);
        iv_google = (ImageView) findViewById(R.id.iv_google);
        iv_image = (ImageView)findViewById(R.id.iv_image);

        dialog = new ProgressDialog(MainActivity.this);
        dialog.setMessage("Loading..");
        dialog.setTitle("Please Wait");
        dialog.setCancelable(false);

        mAuth = FirebaseAuth.getInstance();
        mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                FirebaseUser user = firebaseAuth.getCurrentUser();
                if (user != null) {
                    // User is signed in
                    Log.d("LoginActivity", "onAuthStateChanged:signed_in:" + user.getUid());
                } else {
                    // User is signed out
                    Log.d("LoginActivity", "onAuthStateChanged:signed_out");
                }
                // [START_EXCLUDE]
                updateUI(user);
                // [END_EXCLUDE]
            }
        };


        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken(getString(R.string.default_web_client_id))
                .requestEmail()
                .build();

        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .enableAutoManage(MainActivity.this /* FragmentActivity */, this /* OnConnectionFailedListener */)
                .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                .build();
    }

    private void listener() {
        iv_google.setOnClickListener(this);
        tv_google.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.iv_google:
                break;
            case R.id.tv_google:
                if (boolean_google){
                    signOut();
                    tv_name.setText("");
                    tv_email.setText("");
                    boolean_google=false;
                    Glide.with(MainActivity.this).load(R.drawable.profileimage).into(iv_image);
                }else {
                    signIn();
                }
                break;
        }

    }

    @Override
    public void onStart() {
        super.onStart();
        mAuth.addAuthStateListener(mAuthListener);
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mAuthListener != null) {
            mAuth.removeAuthStateListener(mAuthListener);
        }
    }

    @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) {
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
            if (result.isSuccess()) {
                // Google Sign In was successful, authenticate with Firebase
                GoogleSignInAccount account = result.getSignInAccount();
                firebaseAuthWithGoogle(account);
            } else {
                // Google Sign In failed, update UI appropriately
                // [START_EXCLUDE]
                updateUI(null);
                // [END_EXCLUDE]
            }
        }

    }

    private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
        Log.d("LoginActivity", "firebaseAuthWithGoogle:" + acct.getId());
        // [START_EXCLUDE silent]
        try {

            dialog.show();
        } catch (Exception e) {

        }
        // [END_EXCLUDE]

        AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
        mAuth.signInWithCredential(credential)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        Log.d("LoginActivity", "signInWithCredential:onComplete:" + task.isSuccessful());

                        // If sign in fails, display a message to the user. If sign in succeeds
                        // the auth state listener will be notified and logic to handle the
                        // signed in user can be handled in the listener.
                        if (!task.isSuccessful()) {
                            Log.w("LoginActivity", "signInWithCredential", task.getException());
                            Toast.makeText(MainActivity.this, "Authentication failed.",
                                    Toast.LENGTH_SHORT).show();
                        }
                        // [START_EXCLUDE]

                        try {

                            dialog.dismiss();
                        } catch (Exception e) {

                        }
                        // [END_EXCLUDE]
                    }
                });
    }

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

    private void signOut() {
        // Firebase sign out
        try {
            mAuth.signOut();

            // Google sign out
            Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
                    new ResultCallback<Status>() {
                        @Override
                        public void onResult(@NonNull Status status) {
                            updateUI(null);
                        }
                    });
        } catch (Exception e) {

        }
    }

    private void updateUI(FirebaseUser user) {
        try {
            dialog.dismiss();
        } catch (Exception e) {

        }

        if (user != null) {
            String str_emailgoogle = user.getEmail();
            Log.e("Email", str_emailgoogle);
            tv_email.setText(str_emailgoogle);
            tv_name.setText(user.getDisplayName());
            boolean_google=true;
            tv_google.setText("Sign out from Google");

            Glide.with(MainActivity.this).load( user.getPhotoUrl()).into(iv_image);


            Log.e("Profile", user.getPhotoUrl() + "");

        } else {

        }
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        // An unresolvable error has occurred and Google APIs (including Sign-In) will not
        // be available.
        Log.d("LoginActivity", "onConnectionFailed:" + connectionResult);
        Toast.makeText(this, "Google Play Services error.", Toast.LENGTH_SHORT).show();
    }
}
package com.deepshikha.googlepluslogin;
导入android.app.ProgressDialog;
导入android.content.Intent;
导入android.support.annotation.NonNull;
导入android.support.v4.app.FragmentActivity;
导入android.support.v7.app.AppActivity;
导入android.os.Bundle;
导入android.util.Log;
导入android.view.view;
导入android.widget.ImageView;
导入android.widget.TextView;
导入android.widget.Toast;
导入com.bumptech.glide.glide;
导入com.google.android.gms.auth.api.auth;
导入com.google.android.gms.auth.api.signin.GoogleSignInAccount;
导入com.google.android.gms.auth.api.signin.GoogleSignInOptions;
导入com.google.android.gms.auth.api.signin.GoogleSignInResult;
导入com.google.android.gms.common.ConnectionResult;
导入com.google.android.gms.common.api.GoogleAppClient;
导入com.google.android.gms.common.api.ResultCallback;
导入com.google.android.gms.common.api.Status;
导入com.google.android.gms.tasks.OnCompleteListener;
导入com.google.android.gms.tasks.Task;
导入com.google.firebase.auth.AuthCredential;
导入com.google.firebase.auth.AuthResult;
导入com.google.firebase.auth.FirebaseAuth;
导入com.google.firebase.auth.FirebaseUser;
导入com.google.firebase.auth.GoogleAuthProvider;
公共类MainActivity扩展AppCompativeActivity实现View.OnClickListener、GoogleAppClient.OnConnectionFailedListener{
专用静态最终输入RC\U符号\U IN=9001;
私人消防队;
私有FirebaseAuth.AuthStateListener mAuthListener;
私人GoogleapClient MGoogleapClient;
ImageView iv_谷歌;
进程对话;
ImageView iv_图像;
布尔运算;
text查看电视名称、电视电子邮件、电视谷歌;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
监听器();
}
package com.deepshikha.googlepluslogin;

import android.app.ProgressDialog;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
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.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
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 MainActivity extends AppCompatActivity implements View.OnClickListener, GoogleApiClient.OnConnectionFailedListener {

    private static final int RC_SIGN_IN = 9001;
    private FirebaseAuth mAuth;
    private FirebaseAuth.AuthStateListener mAuthListener;
    private GoogleApiClient mGoogleApiClient;
    ImageView iv_google;
    ProgressDialog dialog;
    ImageView iv_image;

    boolean boolean_google;
    TextView tv_name, tv_email, tv_google;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        init();
        listener();

    }

    private void init() {

        tv_name = (TextView) findViewById(R.id.tv_name);
        tv_email = (TextView) findViewById(R.id.tv_email);
        tv_google = (TextView) findViewById(R.id.tv_google);
        iv_google = (ImageView) findViewById(R.id.iv_google);
        iv_image = (ImageView)findViewById(R.id.iv_image);

        dialog = new ProgressDialog(MainActivity.this);
        dialog.setMessage("Loading..");
        dialog.setTitle("Please Wait");
        dialog.setCancelable(false);

        mAuth = FirebaseAuth.getInstance();
        mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                FirebaseUser user = firebaseAuth.getCurrentUser();
                if (user != null) {
                    // User is signed in
                    Log.d("LoginActivity", "onAuthStateChanged:signed_in:" + user.getUid());
                } else {
                    // User is signed out
                    Log.d("LoginActivity", "onAuthStateChanged:signed_out");
                }
                // [START_EXCLUDE]
                updateUI(user);
                // [END_EXCLUDE]
            }
        };


        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken(getString(R.string.default_web_client_id))
                .requestEmail()
                .build();

        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .enableAutoManage(MainActivity.this /* FragmentActivity */, this /* OnConnectionFailedListener */)
                .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                .build();
    }

    private void listener() {
        iv_google.setOnClickListener(this);
        tv_google.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.iv_google:
                break;
            case R.id.tv_google:
                if (boolean_google){
                    signOut();
                    tv_name.setText("");
                    tv_email.setText("");
                    boolean_google=false;
                    Glide.with(MainActivity.this).load(R.drawable.profileimage).into(iv_image);
                }else {
                    signIn();
                }
                break;
        }

    }

    @Override
    public void onStart() {
        super.onStart();
        mAuth.addAuthStateListener(mAuthListener);
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mAuthListener != null) {
            mAuth.removeAuthStateListener(mAuthListener);
        }
    }

    @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) {
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
            if (result.isSuccess()) {
                // Google Sign In was successful, authenticate with Firebase
                GoogleSignInAccount account = result.getSignInAccount();
                firebaseAuthWithGoogle(account);
            } else {
                // Google Sign In failed, update UI appropriately
                // [START_EXCLUDE]
                updateUI(null);
                // [END_EXCLUDE]
            }
        }

    }

    private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
        Log.d("LoginActivity", "firebaseAuthWithGoogle:" + acct.getId());
        // [START_EXCLUDE silent]
        try {

            dialog.show();
        } catch (Exception e) {

        }
        // [END_EXCLUDE]

        AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
        mAuth.signInWithCredential(credential)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        Log.d("LoginActivity", "signInWithCredential:onComplete:" + task.isSuccessful());

                        // If sign in fails, display a message to the user. If sign in succeeds
                        // the auth state listener will be notified and logic to handle the
                        // signed in user can be handled in the listener.
                        if (!task.isSuccessful()) {
                            Log.w("LoginActivity", "signInWithCredential", task.getException());
                            Toast.makeText(MainActivity.this, "Authentication failed.",
                                    Toast.LENGTH_SHORT).show();
                        }
                        // [START_EXCLUDE]

                        try {

                            dialog.dismiss();
                        } catch (Exception e) {

                        }
                        // [END_EXCLUDE]
                    }
                });
    }

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

    private void signOut() {
        // Firebase sign out
        try {
            mAuth.signOut();

            // Google sign out
            Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
                    new ResultCallback<Status>() {
                        @Override
                        public void onResult(@NonNull Status status) {
                            updateUI(null);
                        }
                    });
        } catch (Exception e) {

        }
    }

    private void updateUI(FirebaseUser user) {
        try {
            dialog.dismiss();
        } catch (Exception e) {

        }

        if (user != null) {
            String str_emailgoogle = user.getEmail();
            Log.e("Email", str_emailgoogle);
            tv_email.setText(str_emailgoogle);
            tv_name.setText(user.getDisplayName());
            boolean_google=true;
            tv_google.setText("Sign out from Google");

            Glide.with(MainActivity.this).load( user.getPhotoUrl()).into(iv_image);


            Log.e("Profile", user.getPhotoUrl() + "");

        } else {

        }
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        // An unresolvable error has occurred and Google APIs (including Sign-In) will not
        // be available.
        Log.d("LoginActivity", "onConnectionFailed:" + connectionResult);
        Toast.makeText(this, "Google Play Services error.", Toast.LENGTH_SHORT).show();
    }
}