Firebase Google身份验证错误

时间:2017-05-27 07:13:08

标签: java android firebase

你好我一直在研究一个Android应用程序的项目,所以我使用firebase android google身份验证,但当我启动应用程序和登录它工作正常,关闭应用程序并重新启动它应用卡在白色屏幕上请帮助我发布我的文件以下

googleutil.java

public class GoogleUtil {

    public static boolean getBooleanPreference(Context context, String key, boolean defaultValue) {

        boolean value = defaultValue;

        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);

        if (preferences != null) {

            value = preferences.getBoolean(key, defaultValue);

        }

        return value;

    }

    public static boolean setBooleanPreference(Context context, String key, boolean value) {

        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);

        if (preferences != null) {

            SharedPreferences.Editor editor = preferences.edit();

            editor.putBoolean(key, value);

            return editor.commit();

        }

        return false;

    }

}

google.java

public class Google {

    private static final int RC_SIGN_IN = 10;

    private GoogleApiClient mGoogleApiClient;

    private FragmentActivity context;

    private OnInfoLoginGoogleCallback mGoogleCallback;

    public Google(FragmentActivity context, OnInfoLoginGoogleCallback mGoogleCallback) {

        this.context = context;

        this.mGoogleCallback = mGoogleCallback;

        getConfigDefaultLogin();

    }

    private void getConfigDefaultLogin() {

        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)

                .requestIdToken(context.getString(R.string.default_web_client_id))

                // TODO: 25-05-2017 Check With JSON default_web_client_id !!! Important

                .requestEmail()

                .build();

        mGoogleApiClient = new GoogleApiClient.Builder(context)

                .enableAutoManage(context /* FragmentActivity */, new GoogleApiClient.OnConnectionFailedListener() {

                    @Override

                    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

                        mGoogleCallback.connectionFailedApiClient(connectionResult);

                    }

                }).addApi(Auth.GOOGLE_SIGN_IN_API, gso).build();

    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == RC_SIGN_IN) {

            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);

            if (result.isSuccess()) {

                GoogleSignInAccount account = result.getSignInAccount();

                firebaseAuthWithGoogle(account);

            } else {

                mGoogleCallback.loginFailed();

            }

        }

    }

    public void signIn() {

        Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);

        context.startActivityForResult(signInIntent, RC_SIGN_IN);

    }

    private void firebaseAuthWithGoogle(final GoogleSignInAccount acct) {

        FirebaseAuth auth = FirebaseAuth.getInstance();

        AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);

        auth.signInWithCredential(credential).addOnCompleteListener(context, new OnCompleteListener<AuthResult>() {

            @Override

            public void onComplete(@NonNull Task<AuthResult> task) {

                if (!task.isSuccessful()) {

                    mGoogleCallback.loginFailed();

                } else {

                    mGoogleCallback.getInfoLoginGoogle(acct);

                }

            }

        });

    }

    public interface OnInfoLoginGoogleCallback {

        void getInfoLoginGoogle(GoogleSignInAccount account);

        void connectionFailedApiClient(ConnectionResult connectionResult);

        void loginFailed();

    }

}

最后在主要活动中实施所有这些

public class MainActivity extends AppCompatActivity implements View.OnClickListener, Google.OnInfoLoginGoogleCallback {

    private static final String USER_ROOT = "User";

    private static final String KEY_LOGIN = "Key_Login";

    private Google mGoogleSign;

    private ProgressBar mProgressBar;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        Window window = getWindow();

        window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);

        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);

        window.setStatusBarColor(Color.TRANSPARENT);

        setContentView(R.layout.activity_main);

        TextView server_load = (TextView) findViewById(R.id.secure_key);

        server_load.setText("Server Secure " + Math.random() + " Key");

        firstShow();

        if (GoogleUtil.getBooleanPreference(this, KEY_LOGIN, false)) {

            startActivity(new Intent(this, MainActivity.class));

            finish();

        }

        initViews();

    }

    private void firstShow() {

        SharedPreferences sharedPreferences = getSharedPreferences("app", MODE_PRIVATE);

        if (sharedPreferences.getBoolean("isFirst", true)) {

            Intent intent = new Intent(MainActivity.this, OnboardingActivity.class);

            startActivity(intent);

            SharedPreferences.Editor editor = sharedPreferences.edit();

            editor.putBoolean("isFirst", false);

            editor.apply();

        }

    }

    @Override

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);

        mGoogleSign.onActivityResult(requestCode, resultCode, data);

    }

    @Override

    public void onClick(View view) {

        switch (view.getId()) {

            case R.id.sign_in_trigger:

                signInGoogle();

                break;

        }

    }

    @Override

    public void getInfoLoginGoogle(GoogleSignInAccount account) {

        sendUserFirebase();

    }

    @Override

    public void connectionFailedApiClient(ConnectionResult connectionResult) {

        addProgressBar(false);

        toast("Error Play Services COD" + connectionResult);

    }

    @Override

    public void loginFailed() {

        addProgressBar(false);

        toast("Login Failed");

    }

    private void initViews() {

        mGoogleSign = new Google(this, this);

        Button mBtnGoogleplus = (Button) findViewById(R.id.sign_in_trigger);

        mProgressBar = (ProgressBar) findViewById(R.id.sign_in_progress_bar);

        mBtnGoogleplus.setOnClickListener(this);

    }

    private void signInGoogle() {

        mGoogleSign.signIn();

        addProgressBar(true);

    }

    private void toast(String mensage) {

        Toast.makeText(this, mensage, Toast.LENGTH_LONG).show();

    }

    private void addProgressBar(boolean flag) {

        mProgressBar.setVisibility(flag ? View.VISIBLE : View.GONE);

    }

    private void sendUserFirebase() {

        DatabaseReference referenceUser = FirebaseDatabase.getInstance().getReference().child(USER_ROOT);

        FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();

        if (firebaseUser != null) {

            User user = new User();

            user.setName(firebaseUser.getDisplayName());

            user.setEmail(firebaseUser.getEmail());

            user.setPhotoUrl(firebaseUser.getPhotoUrl() == null ? "default_uri" : firebaseUser.getPhotoUrl().toString());

            user.setuId(firebaseUser.getUid());

            referenceUser.child(firebaseUser.getUid()).setValue(user).addOnCompleteListener(this, new OnCompleteListener<Void>() {

                @Override

                public void onComplete(@NonNull Task<Void> task) {

                    if (task.isSuccessful()) {

                        GoogleUtil.setBooleanPreference(MainActivity.this, KEY_LOGIN, true);

                        startActivity(new Intent(MainActivity.this, FeedActivity.class));

                        finish();

                    } else {

                        toast("Login Failed Send User, try again.");

                    }

                    addProgressBar(false);

                }

            });

        }

    }

}

我还使用User.java将用户电子邮件发送到数据库

User.java

public class User {

    private String Name;

    private String Email;

    private String UID;

    private String PhotoURL;

    public User() {

    }

    public User(String name, String email, String uId, String photoUrl) {

        this.Name = name;

        this.Email = email;

        this.UID = uId;

        this.PhotoURL = photoUrl;

    }

    public String getName() {

        return Name;

    }

    public void setName(String name) {

        this.Name = name;

    }

    public String getEmail() {

        return Email;

    }

    public void setEmail(String email) {

        this.Email = email;

    }

    public String getuId() {

        return UID;

    }

    public void setuId(String uId) {

        this.UID = uId;

    }

    public String getPhotoUrl() {

        return PhotoURL;

    }

    public void setPhotoUrl(String photoUrl) {

        this.PhotoURL = photoUrl;

    }

}

1 个答案:

答案 0 :(得分:0)

代码太多了。 据我所知,您需要在后台进行一些静默登录。 干得好: OptionalPendingResult示例:

// LogIN pending result
mGoogleApiClientPendingResult = Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient);
    if (mGoogleApiClientPendingResult.isDone()) {
        // There's immediate result available.
        // Handle you result here
        handleSignInResult(mGoogleApiClientPendingResult.get());
    } else {
        // There's no immediate result ready, displays some progress indicator and waits for the
        // async callback.
        mGoogleApiClientPendingResult.setResultCallback(new ResultCallback<GoogleSignInResult>() {
            @Override
            public void onResult(@NonNull GoogleSignInResult result) {
                // Handle you result here
                handleSignInResult(result);
            }
        });
    }

主要活动示例:

private static final int RC_SIGN_IN = 28;
private static final String RC_SIGN_IN_TAG = "GoogleSignIn";
private GoogleApiClient mGoogleApiClient;
private OptionalPendingResult<GoogleSignInResult> mGoogleApiClientPendingResult;

@Override
    protected void onCreate(Bundle savedInstanceState) {

// Google Log In
        // 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 googleSignInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                // Change this for Your needs
                .requestScopes(new Scope(Scopes.DRIVE_APPFOLDER), new Scope(Scopes.DRIVE_FILE), new Scope(Scopes.PROFILE))
                .requestEmail()
                .build();
        // Build a GoogleApiClient with access to the Google Sign-In API and the
        // options specified by gso.
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .enableAutoManage(this, new GoogleApiClient.OnConnectionFailedListener() {
                    @Override
                    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
                        //
                    }
                })
                .addApi(Auth.GOOGLE_SIGN_IN_API, googleSignInOptions)
                .addApi(Drive.API)
                .addScope(Drive.SCOPE_APPFOLDER)
                .addScope(Drive.SCOPE_FILE)
                .build();
        // LogIN pending result
        mGoogleApiClientPendingResult = Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient);
        if (mGoogleApiClientPendingResult.isDone()) {
            // There's immediate result available.
            // Handle you result here
            handleSignInResult(mGoogleApiClientPendingResult.get());
        } else {
            // There's no immediate result ready, displays some progress indicator and waits for the
            // async callback.
            mGoogleApiClientPendingResult.setResultCallback(new ResultCallback<GoogleSignInResult>() {
                @Override
                public void onResult(@NonNull GoogleSignInResult result) {
                    // Handle you result here
                    handleSignInResult(result);
                }
            });
        }
}

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == RC_SIGN_IN) {
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
            handleSignInResult(result);
        }

    }

private void handleSignInResult(GoogleSignInResult result) {
        Log.d(RC_SIGN_IN_TAG, "handleSignInResult:" + result.isSuccess());
        if (result.isSuccess()) {
            // Signed in successfully, show authenticated UI.
            GoogleSignInAccount acct = result.getSignInAccount();
            if (acct != null) {
                // Do your things here
                nameTextView.setText(acct.getDisplayName());
                emailTextView.setText(acct.getEmail());
                // You can gat methods here - https://developers.google.com/android/reference/com/google/android/gms/auth/api/signin/GoogleSignInAccount
            }
        }
    }