Google登录无法自动启动

时间:2018-06-05 09:00:52

标签: android google-signin

我已经在我的Android应用中实施了 Google登录,以便使用Google的Firebase数据库。我已按照Google文档中的所有步骤操作,登录本身正常运行。在启动时,应用程序会检查是否已有登录帐户并直接打开主要意图。我的问题是当用户第一次进行登录时。弹出窗体的窗口,用户输入其凭据。当所有内容都已经过检查时,Google登录弹出窗口会消失,然后会返回我的登录意图,其样式更褪色(我不知道这是否正常)以及用户是否想成为重定向到主要意图,他必须再次点击“谷歌登录按钮”,他被重定向(无需再次输入凭据)。你知道可能导致这个问题的原因吗?登录是可用的,这个小的修正可能对用户来说有点无聊...... 以下是我的完整Google Signin API代码:

public class LoginActivity extends AppCompatActivity
{
//SharedPreferences prefs = null;
private SignInButton mGoogleBtn;
private static final int RC_SIGN_IN = 1;
private GoogleApiClient mGoogleApiClient;
private FirebaseAuth mAuth;
private static final String TAG = "LOGIN_ACTIVITY";
private FirebaseAuth.AuthStateListener mAuthListener;
private DatabaseReference mDatabase;

@Override
/**************************************** Função principal *****************************************/
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    /************************ ESCONDER BARRA DE NAVEGAÇÃO ************************/
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
    {
        int UI_OPTIONS = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
        getWindow().getDecorView().setSystemUiVisibility(UI_OPTIONS);
    }

mAuth = FirebaseAuth.getInstance();

mGoogleBtn = findViewById(R.id.btnGoogle);
    /* Configurar o Signin do Google */
    GoogleSignInOptions gso = new 
GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestIdToken(getString(R.string.default_web_client_id))
            .requestEmail()
            .build();

    mGoogleApiClient = new GoogleApiClient.Builder(getApplicationContext())
            .enableAutoManage(this, new GoogleApiClient.OnConnectionFailedListener()
            {
                @Override
                public void onConnectionFailed(@NonNull ConnectionResult connectionResult)
                {
                    Toast.makeText(LoginActivity.this, "You got an Error", Toast.LENGTH_LONG).show();
                }
            })
            .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
            .build();

    /* Caso o utilizador tenha carregado no botão de SignIn, executa esta função */
    mGoogleBtn.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View view)
        {
            signIn();
        }
    });

    /***************************************** Declarações *****************************************/
    /* TextViews */
    TextView txtTituloLogin = findViewById(R.id.txtTitleLogin);
    TextView txtDescLogin = findViewById(R.id.txtDescLogin);

    /* TypeFaces */
    Typeface tpTitulos = Typeface.createFromAsset(getAssets(),"fonts/RobotoSlab-Bold.ttf");
    Typeface tpDesc = Typeface.createFromAsset(getAssets(),"fonts/RobotoSlab-Light.ttf");
    /************************************* Fim das declarações *************************************/

    /* Adiciona a TypeFace às TextViews */
    txtTituloLogin.setTypeface(tpTitulos);
    txtDescLogin.setTypeface(tpDesc);

    /***************************************** Login *****************************************/
    /* Verifica se o utilizador atual é diferente de nulo, caso seja, abre a Main Activity */
    mAuthListener = new FirebaseAuth.AuthStateListener()
    {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth)
        {
            if(firebaseAuth.getCurrentUser() != null)
            {
                Intent intentSplash = new Intent(LoginActivity.this, MainActivity.class); // Cria o intent "intentSplash"
                startActivity(intentSplash); // Começa o intent para a SplashActivity
                finish();
            }
        }
    };
    /***************************************** Fim do Login *****************************************/
/***************************************** Fim da função principal *****************************************/
}

@Override
protected void onStart()
{
    super.onStart();
    mAuth.addAuthStateListener(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())
        {
            /* Caso o Login tenha sido efetuado com sucesso, autentica com a Firebase*/
            GoogleSignInAccount account = result.getSignInAccount();
            firebaseAuthWithGoogle(account);
        }
       // else
       // {
            // Google Sign In failed, update UI appropriately
            // ...
        //}
    }
}

private void firebaseAuthWithGoogle(GoogleSignInAccount account) {

    AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
    mAuth.signInWithCredential(credential)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>()
            {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task)
                {
                    if (task.isSuccessful())
                    {
                        /* Se o login der certo, atualiza as informações do utilizador */
                        Log.d(TAG, "signInWithCredential:success");
                        FirebaseUser user = mAuth.getCurrentUser();
                        Global.google_profile_id = user.getUid();
                        Global.google_full_name = user.getDisplayName();
                        Global.google_email = user.getEmail();
                        Global.google_profile_pic = user.getPhotoUrl();
                        SharedPreferences sp = 
PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
                        SharedPreferences.Editor editor;
                        editor = getSharedPreferences("GoogleInfo", 
MODE_PRIVATE).edit();

editor.putString("google_profile_id",Global.google_profile_id);

editor.putString("google_full_name",Global.google_full_name);

editor.putString("google_email",Global.google_email);
                        editor.putString("google_profile_pic", 
String.valueOf(Global.google_profile_pic));
                        editor.apply();
                        /* Faz uma referência à Base de Dados */
                        mDatabase = 
FirebaseDatabase.getInstance().getReference();


Database.child("utilizadores").
child(Global.google_profile_id).child("Nome").
setValue(Global.google_full_name); 



mDatabase.child("utilizadores").
child(Global.google_profile_id).
child("Email").setValue(Global.google_email); 
                        //updateUI(user);
                    }
                    else
                    {
                        /* Se o login der erro, mostra a mensagem ao 
utilizador*/
                        Log.w(TAG, "signInWithCredential:failure", 
task.getException());
                        Toast.makeText(LoginActivity.this, "Erro ao efetuar 
o login.", // Mensagem de erro
                        Toast.LENGTH_SHORT).show();
                       // updateUI(null);
                    }

                    // ...
                }
            });
}

这个updateUI(null);在评论中,因为如果我取消注释,它会获得红色错误颜色表示它无法解析该方法。这updateUI(null);是否与我遇到的问题有关?有谁知道这行代码使用了什么?与updateUI(user);

相同

0 个答案:

没有答案