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

Android Studio中FirebaseAuth初始化失败问题排查与解决

FirebaseAuth.getInstance()执行崩溃的原因分析与解决思路

在Android Studio(Java)项目中开发Firebase功能时,执行FirebaseAuth.getInstance();代码行时应用崩溃,配置看似无误但错误反复出现。相关代码如下:

App级build.gradle文件

plugins {
    id 'com.android.application'
    id 'com.google.gms.google-services'
}

android {
    namespace 'com.example.grocereasy'
    compileSdk 33

    defaultConfig {
        applicationId "com.example.grocereasy"
        minSdk 23
        targetSdk 33
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {

    implementation 'androidx.appcompat:appcompat:1.6.1'
    implementation 'com.google.android.material:material:1.9.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
    implementation 'com.google.firebase:firebase-auth:22.2.0'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.5'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
    implementation 'com.google.android.gms:play-services-gcm:17.0.0'

}

RegisterActivity代码

package com.example.grocereasy;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.Firebase;
import com.google.firebase.FirebaseApp;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;

public class RegisterActivity extends AppCompatActivity {

    Button signupBtn;
    EditText name, email, password;
    TextView login;
    FirebaseAuth auth;


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

        auth = FirebaseAuth.getInstance();

        signupBtn = findViewById(R.id.signupBtn);
        name = findViewById(R.id.regName);
        email = findViewById(R.id.regEmail);
        password = findViewById(R.id.regPassword);
        login = findViewById(R.id.goToLogin);

        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
            }
        });

        signupBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                createUser();
            }
        });

    }

    private void createUser(){
        String userName = name.getText().toString();
        String userEmail = email.getText().toString();
        String userPassword = password.getText().toString();

        if(TextUtils.isEmpty(userName) || TextUtils.isEmpty(userEmail) || TextUtils.isEmpty(userPassword)){
            Toast.makeText(this, "Fill all fields", Toast.LENGTH_SHORT).show();
            return;
        }
        if(userPassword.length() > 6){
            Toast.makeText(this, "Password must be grater then 6 characters", Toast.LENGTH_SHORT).show();
            return;
        }

        auth.createUserWithEmailAndPassword(userEmail, userPassword)
                .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            Toast.makeText(RegisterActivity.this, "Registration successful", Toast.LENGTH_SHORT).show();
                        }else {
                            Toast.makeText(RegisterActivity.this, "Error: "+task.getException(), Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }
}

可能的崩溃原因

  1. Firebase配置文件问题:google-services.json未正确放置或文件内容与Firebase控制台项目不匹配,导致Firebase无法识别应用身份。
  2. 项目级Google服务插件缺失:项目根目录的build.gradle未配置Google服务插件的classpath,导致app级插件无法正常工作。
  3. Firebase初始化时机错误:在FirebaseApp未完成初始化时就调用FirebaseAuth.getInstance(),引发初始化异常。
  4. 依赖版本冲突:Firebase Auth与Google Play服务(如play-services-gcm)的版本不兼容,导致运行时依赖冲突。
  5. 网络权限缺失:应用未声明网络权限,Firebase无法完成初始化请求。

解决思路

  1. 验证配置文件
    • 从Firebase控制台重新下载对应项目的google-services.json,确保文件中的package_name与项目applicationId完全一致。
    • 将文件放置在app模块的根目录下,确保Android Studio能正确识别。
  2. 补充项目级配置
    • 打开项目根目录的build.gradle,在dependencies块中添加Google服务插件依赖:
      dependencies {
          // 其他classpath
          classpath 'com.google.gms:google-services:4.4.0' // 或最新兼容版本
      }
      
  3. 确保Firebase先初始化
    • 在onCreate方法开头主动初始化FirebaseApp:
      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          FirebaseApp.initializeApp(this); // 添加这行
          setContentView(R.layout.activity_register);
          auth = FirebaseAuth.getInstance();
          // 其他代码
      }
      
  4. 统一依赖版本
    • 使用Firebase BoM管理所有Firebase依赖版本,避免版本冲突:
      在app级build.gradle的dependencies块中添加:
      implementation platform('com.google.firebase:firebase-bom:32.3.1') // 最新稳定版
      implementation 'com.google.firebase:firebase-auth' // 去掉版本号,由BoM管理
      
    • 移除play-services-gcm依赖(如果不需要GCM功能),或确保其版本与Firebase依赖兼容。
  5. 添加网络权限
    • 在AndroidManifest.xml中添加网络权限:
      <uses-permission android:name="android.permission.INTERNET"/>
      
  6. 清理重建项目
    • 执行Build -> Clean Project,再执行Build -> Rebuild Project,清除构建缓存后重新编译。

内容的提问来源于stack exchange,提问作者Santhosh . M

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 00:45:00