如何通过Gradle任务自动为Android Flavor配置Firebase的google-services.json
Absolutely! You can automate the entire process of registering Firebase apps for your Android flavors, downloading the google-services.json files, and placing them in the correct directories using custom Gradle tasks paired with Firebase's Admin API. Let me walk you through how to set this up step by step:
1. Prerequisites First
Before diving into code, make sure you have these ready:
- A Firebase project (obviously)
- A service account key JSON file for your Firebase project:
- Go to your Firebase Console → Project Settings → Service Accounts
- Click "Generate New Private Key" and save the file as
firebase-service-account.jsonin your project root - Critical: Add this file to your
.gitignoreimmediately—never commit it to version control!
- The latest Firebase Admin SDK dependency added to your build setup
2. Add Firebase Admin SDK to Gradle
In your project-level build.gradle (or build.gradle.kts if you use Kotlin DSL), add the Admin SDK to the buildscript dependencies:
Groovy (build.gradle)
buildscript { dependencies { classpath 'com.google.firebase:firebase-admin:9.2.0' // Use the latest version available } }
Kotlin DSL (build.gradle.kts)
buildscript { dependencies { classpath("com.google.firebase:firebase-admin:9.2.0") // Use the latest version available } }
3. Create the Custom Gradle Task
In your app module's build.gradle/build.gradle.kts, add a task that handles app registration, config download, and file placement for each flavor.
Groovy Implementation
import com.google.firebase.FirebaseApp import com.google.firebase.FirebaseOptions import com.google.firebase.projectmanagement.FirebaseProjectManagement // Replace with your actual Firebase project ID def firebaseProjectId = "your-firebase-project-id" def serviceAccountFile = file("firebase-service-account.json") // Initialize Firebase Admin SDK def options = FirebaseOptions.builder() .setCredentials(com.google.auth.oauth2.GoogleCredentials.fromStream(serviceAccountFile.newInputStream())) .setProjectId(firebaseProjectId) .build() FirebaseApp.initializeApp(options) def projectManagement = FirebaseProjectManagement.getInstance() // Task to setup Firebase for all flavors task setupFirebaseForFlavors { doLast { android.productFlavors.each { flavor -> def packageName = flavor.applicationId def flavorDir = file("src/${flavor.name}") def googleServicesFile = new File(flavorDir, "google-services.json") // Check if the app already exists in Firebase def existingApps = projectManagement.listAndroidApps() def appExists = existingApps.any { it.getPackageName() == packageName } // Create app if it doesn't exist if (!appExists) { println "Creating Firebase app for flavor: ${flavor.name} (package: $packageName)" projectManagement.createAndroidApp(packageName, flavor.name) } // Download and save the google-services.json println "Fetching google-services.json for flavor: ${flavor.name}" def app = projectManagement.getAndroidApp(packageName) def jsonContent = app.getConfig() googleServicesFile.parentFile.mkdirs() // Create flavor directory if it doesn't exist googleServicesFile.write(jsonContent) } } } // Optional: Run this task automatically before every build preBuild.dependsOn setupFirebaseForFlavors
Kotlin DSL Implementation
import com.google.firebase.FirebaseApp import com.google.firebase.FirebaseOptions import com.google.firebase.projectmanagement.FirebaseProjectManagement // Replace with your actual Firebase project ID val firebaseProjectId = "your-firebase-project-id" val serviceAccountFile = file("firebase-service-account.json") // Initialize Firebase Admin SDK val options = FirebaseOptions.builder() .setCredentials(com.google.auth.oauth2.GoogleCredentials.fromStream(serviceAccountFile.inputStream())) .setProjectId(firebaseProjectId) .build() FirebaseApp.initializeApp(options) val projectManagement = FirebaseProjectManagement.getInstance() // Task to setup Firebase for all flavors tasks.register("setupFirebaseForFlavors") { doLast { android.productFlavors.forEach { flavor -> val packageName = flavor.applicationId.get() val flavorDir = file("src/${flavor.name}") val googleServicesFile = File(flavorDir, "google-services.json") // Check if the app already exists in Firebase val existingApps = projectManagement.listAndroidApps() val appExists = existingApps.any { it.packageName == packageName } // Create app if it doesn't exist if (!appExists) { println("Creating Firebase app for flavor: ${flavor.name} (package: $packageName)") projectManagement.createAndroidApp(packageName, flavor.name) } // Download and save the google-services.json println("Fetching google-services.json for flavor: ${flavor.name}") val app = projectManagement.getAndroidApp(packageName) val jsonContent = app.config googleServicesFile.parentFile.mkdirs() // Create flavor directory if it doesn't exist googleServicesFile.writeText(jsonContent) } } } // Optional: Run this task automatically before every build tasks.preBuild.dependsOn("setupFirebaseForFlavors")
4. Key Notes to Keep in Mind
- Rate Limits: Firebase's Admin API has rate limits, so consider making this a manual task (remove the
preBuild.dependsOnline) instead of running it on every build. Only run it when you add a new flavor. - Version Updates: Always use the latest version of the Firebase Admin SDK to avoid compatibility issues.
- Customization: The code uses the flavor name as the Firebase app's display name—feel free to adjust that in the
createAndroidAppcall if you want a different naming convention. - Alternative: Firebase CLI: If you prefer using the Firebase CLI over the Admin SDK, you can write a shell script that uses commands like
firebase apps:create androidandfirebase apps:sdkconfig android, then call that script from a Gradle task.
内容的提问来源于stack exchange,提问作者Elior
相关产品推荐
相关产品推荐

