You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Firebase集成Google/Facebook登录在低版本Android设备失效问题

Firebase Google/Facebook Login Fails on Android 4.4/5.0 (No Logs) - Fixes & Debugging Steps

Problem Overview

I’ve integrated Firebase-powered Google and Facebook login into my Android app, which works flawlessly on Android 7.0 and higher. But on Android 4.4 (KitKat) and 5.0 (Lollipop) devices, the login feature dies completely—no user feedback, no error logs, nothing. The app is live on Google Play, and I’ve already added the release SHA-1 to the Firebase console.

Core Implementation Code

Here’s the key code for the login flow:

Activity Lifecycle & Login Triggers

@Override 
public void onActivityResult(int requestCode, int resultCode, Intent data) { 
    super.onActivityResult(requestCode, resultCode, data); 
    // Pass result to Facebook SDK
    mCallbackManager.onActivityResult(requestCode, resultCode, data); 
    // Handle Google Sign-In result
    if (requestCode == G_SIGN_IN) { 
        Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data); 
        try { 
            GoogleSignInAccount account = task.getResult(ApiException.class); 
            firebaseAuthWithGoogle(Objects.requireNonNull(account)); 
        } catch (ApiException e) { 
            Tools.createSnackBar(LoginActivity.this,"Google sign in failed! " + e.getLocalizedMessage(),Snackbar.LENGTH_SHORT).show(); 
            Log.d(TAG, e.getLocalizedMessage()); 
            googleBtn.setEnabled(true); 
            pb.hide(); 
        } 
    } 
}

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_login); 
    googleBtn = findViewById(R.id.google_btn); 
    facebookBtn = findViewById(R.id.facebook_btn); 
    pb = findViewById(R.id.pb); 
    pb.hide(); 
    mAuth = FirebaseAuth.getInstance(); 
    functions = new FirebaseFunctions(LoginActivity.this); 

    // Google Sign-In setup
    final GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) 
            .requestIdToken(getString(R.string.clientId)) 
            .requestEmail() 
            .build(); 
    final GoogleSignInClient mGoogleSignInClient = GoogleSignIn.getClient(this, gso); 
    googleBtn.setOnClickListener(v -> { 
        googleBtn.setEnabled(false); 
        pb.show(); 
        Intent signInIntent = mGoogleSignInClient.getSignInIntent(); 
        startActivityForResult(signInIntent, G_SIGN_IN); 
    }); 

    // Facebook Sign-In setup
    mCallbackManager = CallbackManager.Factory.create(); 
    facebookBtn.setOnClickListener(v -> { 
        final LoginManager loginManager = LoginManager.getInstance(); 
        loginManager.logInWithReadPermissions(LoginActivity.this, Arrays.asList(EMAIL, PROFILE)); 
        facebookBtn.setEnabled(false); 
        loginManager.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() { 
            @Override 
            public void onSuccess(LoginResult loginResult) { 
                handleFacebookSignIn(loginResult.getAccessToken()); 
            } 
            @Override 
            public void onCancel() { 
                Tools.createSnackBar(LoginActivity.this,"Login cancelled",Snackbar.LENGTH_SHORT).show(); 
                facebookBtn.setClickable(true); 
            } 
            @Override 
            public void onError(FacebookException error) { 
                Tools.createSnackBar(LoginActivity.this,error.getMessage(),Snackbar.LENGTH_SHORT).show(); 
                Log.d(TAG,error.getLocalizedMessage()); 
                facebookBtn.setClickable(true); 
            } 
        }); 
    }); 
}

Firebase Authentication Handlers

private void firebaseAuthWithGoogle(GoogleSignInAccount acct) { 
    AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null); 
    mAuth.signInWithCredential(credential) 
            .addOnCompleteListener(this, task -> { 
                if (task.isSuccessful()) { 
                    FirebaseUser user = mAuth.getCurrentUser(); 
                    // Add new user to backend
                    if (user != null) { 
                        functions.addNewUser(user.getDisplayName(),user.getEmail(), Objects.requireNonNull(user.getPhotoUrl()).toString(), false, pb); 
                    } 
                } else { 
                    Tools.createSnackBar(LoginActivity.this,"Authentication Failed " + task.getException(),Snackbar.LENGTH_SHORT).show(); 
                    if(task.getException()!=null) { 
                        Log.e(TAG, task.getException().getLocalizedMessage()); 
                    } 
                    googleBtn.setEnabled(true); 
                    pb.hide(); 
                } 
            }); 
}

private void handleFacebookSignIn(AccessToken accessToken) { 
    pb.show(); 
    final AuthCredential credential = FacebookAuthProvider.getCredential(accessToken.getToken()); 
    mAuth.signInWithCredential(credential) 
            .addOnCompleteListener(this, task -> { 
                if (task.isSuccessful()) { 
                    FirebaseUser user = mAuth.getCurrentUser(); 
                    // Add new user to backend
                    if (user != null) { 
                        String email = user.getEmail(); 
                        String photoUrl = Objects.requireNonNull(user.getPhotoUrl()).toString(); 
                        photoUrl = photoUrl + "?height=500"; 
                        if(email==null){ email = "Email not found";} 
                        functions.addNewUser(user.getDisplayName(),email, photoUrl, false, pb); 
                    } 
                } else { 
                    Tools.createSnackBar(LoginActivity.this,"Authentication failed "+task.getException(),Snackbar.LENGTH_SHORT).show(); 
                    if(task.getException()!=null) { 
                        Log.e(TAG, task.getException().getLocalizedMessage()); 
                    } 
                    facebookBtn.setEnabled(true); 
                    pb.hide(); 
                } 
            }); 
}

Debugging & Fix Steps for Android 4.4/5.0

1. Enable TLS 1.2 (Critical Fix)

Android 4.4 and early 5.0 devices don’t enable TLS 1.2 by default, but Firebase, Google, and Facebook all require this secure protocol for API calls. This is almost certainly why your login fails silently (network calls die without errors).

Implementation:
Add this code early in your onCreate (before initializing Firebase or login clients):

try {
    // Install latest TLS/SSL providers from Google Play Services
    ProviderInstaller.installIfNeeded(getApplicationContext());
    SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
    sslContext.init(null, null, null);
    sslContext.createSSLEngine();
} catch (GooglePlayServicesRepairableException e) {
    Log.e(TAG, "Need to update Google Play Services", e);
    // Show dialog to prompt user update
    GoogleApiAvailability.getInstance().showErrorDialogFragment(this, e.getConnectionStatusCode(), 1);
} catch (Exception e) {
    Log.e(TAG, "Failed to initialize TLS 1.2", e);
}

Add the dependency to your module-level build.gradle:

implementation 'com.google.android.gms:play-services-base:18.2.0'

2. Verify App Signing SHA-1

If you use Google Play App Signing, you must use the SHA-1 from the Play Console (App Signing tab), not your local keystore’s SHA-1. Double-check that both debug and release SHA-1s are added to Firebase Console > Project Settings > Your Apps.

3. Fix Logging & User Feedback

Older devices may not support Snackbar, and Logcat might not capture truncated messages. Update your error handling:

  • Use full stack traces in logs: Log.e(TAG, "Google login failed", e) instead of just the localized message.
  • Fall back to Toast for pre-Lollipop devices:
String errorMessage = "Google sign in failed!";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    Tools.createSnackBar(LoginActivity.this, errorMessage + " " + e.getLocalizedMessage(), Snackbar.LENGTH_SHORT).show();
} else {
    Toast.makeText(LoginActivity.this, errorMessage, Toast.LENGTH_SHORT).show();
}

4. Check Google Play Services Version

Outdated Play Services on low-end devices breaks Google Sign-In. Add a check before starting login:

int playServicesStatus = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(this);
if (playServicesStatus != ConnectionResult.SUCCESS) {
    if (GoogleApiAvailability.getInstance().isUserResolvableError(playServicesStatus)) {
        GoogleApiAvailability.getInstance().showErrorDialogFragment(this, playServicesStatus, 2);
    } else {
        Toast.makeText(this, "Google Play Services not supported on this device", Toast.LENGTH_SHORT).show();
        googleBtn.setEnabled(true);
    }
    return;
}

5. Fix Null Pointer Exceptions

The Objects.requireNonNull() method was added in API 24—it will crash Android 4.4 devices. Replace these with explicit null checks:

// Instead of Objects.requireNonNull(account)
if (account == null) {
    Log.e(TAG, "GoogleSignInAccount is null");
    googleBtn.setEnabled(true);
    pb.hide();
    return;
}
firebaseAuthWithGoogle(account);

Do the same for user.getPhotoUrl()—handle null cases gracefully instead of forcing a non-null value.

6. Facebook SDK Compatibility

Ensure you’re using a Facebook SDK version that supports Android 4.4. Check your build.gradle:

implementation 'com.facebook.android:facebook-login:15.1.0' // Or latest compatible version

Also, add android:usesCleartextTraffic="true" to your <application> tag in AndroidManifest.xml if targeting API 28+ (older devices may need this for non-HTTPS redirects).


Final Notes

Test these fixes on physical Android 4.4/5.0 devices (emulators often don’t replicate low-version network issues). The TLS 1.2 fix is the most impactful here—silent network failures are the #1 cause of login issues on older Android versions.

内容的提问来源于stack exchange,提问作者Aman Chatterjee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:14:15