简体   繁体   English

如何检查用户是否已经在 google auth 中登录。 在安卓中

[英]How to check if user is already login in google auth. in android

I'm a new android developer and a student.我是一名新的 android 开发人员和一名学生。 I'm having difficulty of if the user is already login in my app.如果用户已经登录我的应用程序,我会遇到困难。 I will show some of my codes.我将展示我的一些代码。 I greatly appreciate for the help and answer.我非常感谢您的帮助和回答。

Login.java登录.java

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

    OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient);

    if(opr.isDone()) {
        Log.d(TAG,"Got cached sign-in");
        GoogleSignInResult result = opr.get();
        handleSignInResult(result);
    } else {
        SignInButton mGoogleSignInButton = (SignInButton) findViewById(R.id.sign_in_button);
        mStatusView = (TextView) findViewById(R.id.status_text);
        mGoogleSignInButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.sign_in_button:
                        signInWithGoogle();
                }
            }
        });
    }
}
 private void signInWithGoogle(){
    if(mGoogleApiClient != null) {
        mGoogleApiClient.disconnect();
    }

    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail().build();
    mGoogleApiClient = new GoogleApiClient.Builder(this).addApi(Auth.GOOGLE_SIGN_IN_API,gso).build();

    final 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);
        handleSignInResult(result);
    }
}



private void handleSignInResult(GoogleSignInResult result) {
    Log.d(TAG, "handleSignInResult:" + result.isSuccess());
    if(result.isSuccess()) {
        GoogleSignInAccount account = result.getSignInAccount();
        mStatusView.setText(getString(R.string.signed_in_fmt, account.getDisplayName()));
        //TODO: Start another explicit intent here. but this time, start MainActivity
        Intent intent = new Intent(Login.this , MainActivity.class);
        startActivity(intent);
        finish();

    } else {

    }
}

where did i go wrong ?我哪里做错了 ?

For Google Login check whether user is signed in or not:对于 Google 登录,请检查用户是否已登录:

if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
   // User is signed in.
   // ...
} else {
   // User is not signed in. 
   // Perform your operation.
}

GoogleApiClient mGoogleApiClient is deprecated now! GoogleApiClient mGoogleApiClient 现已弃用! So according doc所以根据文档

   // Check for existing Google Sign In account, if the user is already signed in
// the GoogleSignInAccount will be non-null.
GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);
updateUI(account);

For example:例如:

 if (GoogleSignIn.getLastSignedInAccount(context) == null) {
            Log.d(TAG_SIGN_FLOW, "User is not signed in, so make login in")

            val signInOptions: GoogleSignInOptions = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestEmail()
                .requestScopes(Scope(DriveScopes.DRIVE_FILE))
                .build()
            startActivityForResult(GoogleSignIn.getClient(this.requireActivity(), signInOptions).signInIntent, REQUEST_CODE_SIGN_IN)
        } else {
            Log.d(TAG_SIGN_FLOW, "User has already been login")
        }

Assuming that you are checking authentication status from any Activity for eg Main Activity (Incase fragment get a singleton instance of your context from any activity which it is triggered from).假设您正在检查任何活动的身份验证状态,例如主活动(Incase 片段从触发它的任何活动中获取您的上下文的单例实例)。

GoogleApiClient mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(Plus.API)
                .addScope(Plus.SCOPE_PLUS_LOGIN)
                .build();

    if (mGoogleApiClient.isConnected()) {
            //Todo
        }
    }

I know it has been 6 years already but I can try to help.我知道已经 6 年了,但我可以尝试提供帮助。 To check whether user is logged in and immediately open the MainActivity override the on Start method要检查用户是否已登录并立即打开 MainActivity 重写 on Start 方法

   @Override
    protected void onStart() {
    super.onStart()

    FirebaseAuth auth = FirebaseAuth.getInstance();
    FirebaseUser fUser = auth.getCurrentUser();

    if (fUser != null){
     startActivity(new Intent(LoginActivity.this, MainActivity.class));
     }


  }

The above code will do the trick.上面的代码可以解决问题。 Happy coding:)快乐编码:)

Made change in below code-在以下代码中进行了更改-

Maintain a boolean variable in sharedPreferance and will work for you.在 sharedPreferance 中维护一个布尔变量,它将为您工作。

SharedPreferences sharedPreferences;
    SharedPreferences.Editor editor;

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

sharedPreferences =getSharedPreferences(getPackageName(), MODE_PRIVATE);
        editor = sharedPreferences.edit();

if(sharedPreferences.getBoolean("isLogin",false))
{
        Intent intent = new Intent(Login.this , MainActivity.class);
        startActivity(intent);
        finish();
}

    OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient);

    if(opr.isDone()) {
        Log.d(TAG,"Got cached sign-in");
        GoogleSignInResult result = opr.get();
        handleSignInResult(result);
    } else {
        SignInButton mGoogleSignInButton = (SignInButton) findViewById(R.id.sign_in_button);
        mStatusView = (TextView) findViewById(R.id.status_text);
        mGoogleSignInButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.sign_in_button:
                        signInWithGoogle();
                }
            }
        });
    }
}
 private void signInWithGoogle(){
    if(mGoogleApiClient != null) {
        mGoogleApiClient.disconnect();
    }

    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail().build();
    mGoogleApiClient = new GoogleApiClient.Builder(this).addApi(Auth.GOOGLE_SIGN_IN_API,gso).build();

    final 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);
        handleSignInResult(result);
    }
}



private void handleSignInResult(GoogleSignInResult result) {
    Log.d(TAG, "handleSignInResult:" + result.isSuccess());
    if(result.isSuccess()) {
        GoogleSignInAccount account = result.getSignInAccount();
        mStatusView.setText(getString(R.string.signed_in_fmt, account.getDisplayName()));
        //TODO: Start another explicit intent here. but this time, start MainActivity

        sharedPreferences.edit().putBoolean("isLogin",true).apply();
        Intent intent = new Intent(Login.this , MainActivity.class);
        startActivity(intent);
        finish();

    } else {

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何关闭用户会话/身份验证。 在 Spring OAuth2 中为用户/客户端发送访问令牌后的上下文 - How to close user session/auth. context after access token is sent for a user/client in Spring OAuth2 检查用户是否首次使用Firebase身份验证和数据库登录Android应用 - Check if is user first login on Android App using Firebase Auth and Database 如何在电话身份验证期间检查用户是否已存在于 firebase 中 - How to check if a user already exists in firebase during phone auth 如何在 Android 中检查电话身份验证用户? - How to check for a phone auth user in Android? 如何检查用户是否已经通过 gmail 或谷歌帐户登录? - How to check if user is already signed in via gmail or google account? 如何使用 Android Studio 在 firebase 中检查“用户电子邮件已经存在” - How to check "user email already exists" in firebase using Android Studio 如何使用Google登录身份验证我的应用程序? - How to auth my app with Google LogIn? Android Sharedpreference 检查用户是否已经登录 - Android Sharedpreference Check if the user already logged in or not 如何验证用户是否已经登录到ADFS - how to verify if user already login to ADFS Android Google Map 如何检查用户是否在标记矩形区域中 - Android Google Map how to check if user is in marker rectangle region
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM