Skip to content

Commit

Permalink
feat(android,core): allow initializing default Firebase apps via `Fir…
Browse files Browse the repository at this point in the history
…ebaseOptions.fromResource` on Android (#8566)
  • Loading branch information
Salakar committed May 3, 2022
1 parent 7e3048f commit 30216c4
Show file tree
Hide file tree
Showing 12 changed files with 229 additions and 137 deletions.
Expand Up @@ -73,39 +73,43 @@ public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
applicationContext = null;
}

private Task<Map<String, Object>> firebaseAppToMap(FirebaseApp firebaseApp) {
return Tasks.call(
cachedThreadPool,
() -> {
Map<String, Object> appMap = new HashMap<>();
Map<String, String> optionsMap = new HashMap<>();
FirebaseOptions options = firebaseApp.getOptions();
private Map<String, String> firebaseOptionsToMap(FirebaseOptions options) {
Map<String, String> optionsMap = new HashMap<>();

optionsMap.put(KEY_API_KEY, options.getApiKey());
optionsMap.put(KEY_APP_ID, options.getApplicationId());
optionsMap.put(KEY_API_KEY, options.getApiKey());
optionsMap.put(KEY_APP_ID, options.getApplicationId());

if (options.getGcmSenderId() != null) {
optionsMap.put(KEY_MESSAGING_SENDER_ID, options.getGcmSenderId());
}
if (options.getGcmSenderId() != null) {
optionsMap.put(KEY_MESSAGING_SENDER_ID, options.getGcmSenderId());
}

if (options.getProjectId() != null) {
optionsMap.put(KEY_PROJECT_ID, options.getProjectId());
}
if (options.getProjectId() != null) {
optionsMap.put(KEY_PROJECT_ID, options.getProjectId());
}

if (options.getDatabaseUrl() != null) {
optionsMap.put(KEY_DATABASE_URL, options.getDatabaseUrl());
}
if (options.getDatabaseUrl() != null) {
optionsMap.put(KEY_DATABASE_URL, options.getDatabaseUrl());
}

if (options.getStorageBucket() != null) {
optionsMap.put(KEY_STORAGE_BUCKET, options.getStorageBucket());
}
if (options.getStorageBucket() != null) {
optionsMap.put(KEY_STORAGE_BUCKET, options.getStorageBucket());
}

if (options.getGaTrackingId() != null) {
optionsMap.put(KEY_TRACKING_ID, options.getGaTrackingId());
}
if (options.getGaTrackingId() != null) {
optionsMap.put(KEY_TRACKING_ID, options.getGaTrackingId());
}

return optionsMap;
}

private Task<Map<String, Object>> firebaseAppToMap(FirebaseApp firebaseApp) {
return Tasks.call(
cachedThreadPool,
() -> {
Map<String, Object> appMap = new HashMap<>();

appMap.put(KEY_NAME, firebaseApp.getName());
appMap.put(KEY_OPTIONS, optionsMap);
appMap.put(KEY_OPTIONS, firebaseOptionsToMap(firebaseApp.getOptions()));

appMap.put(
KEY_IS_AUTOMATIC_DATA_COLLECTION_ENABLED,
Expand Down Expand Up @@ -173,6 +177,16 @@ private Task<List<Map<String, Object>>> initializeCore() {
});
}

private Task<Map<String, String>> firebaseOptionsFromResource() {
return Tasks.call(
cachedThreadPool,
() -> {
final FirebaseOptions options = FirebaseOptions.fromResource(applicationContext);
if (options == null) return null;
return firebaseOptionsToMap(options);
});
}

private Task<Void> setAutomaticDataCollectionEnabled(Map<String, Object> arguments) {
return Tasks.call(
cachedThreadPool,
Expand Down Expand Up @@ -224,6 +238,9 @@ public void onMethodCall(MethodCall call, @NonNull final MethodChannel.Result re
case "Firebase#initializeCore":
methodCallTask = initializeCore();
break;
case "Firebase#optionsFromResource":
methodCallTask = firebaseOptionsFromResource();
break;
case "FirebaseApp#setAutomaticDataCollectionEnabled":
methodCallTask = setAutomaticDataCollectionEnabled(call.arguments());
break;
Expand Down
@@ -1,61 +1,55 @@
def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
localPropertiesFile.withReader('UTF-8') { reader ->
localProperties.load(reader)
}
localPropertiesFile.withReader('UTF-8') { reader ->
localProperties.load(reader)
}
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
flutterVersionCode = '1'
flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
flutterVersionName = '1.0'
flutterVersionName = '1.0'
}

apply plugin: 'com.android.application'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

android {
compileSdkVersion 29

lintOptions {
disable 'InvalidPackage'
}

defaultConfig {
applicationId "io.flutter.plugins.firebasecoreexample"
minSdkVersion 21
targetSdkVersion 28
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}

buildTypes {
release {
// TODO: Add your own signing config for the release build.
// Signing with the debug keys for now, so `flutter run --release` works.
signingConfig signingConfigs.debug
}
compileSdkVersion flutter.compileSdkVersion

compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}

defaultConfig {
applicationId "io.flutter.plugins.firebasecoreexample"
minSdkVersion flutter.minSdkVersion
targetSdkVersion flutter.targetSdkVersion
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
}

buildTypes {
release {
signingConfig signingConfigs.debug
}
}
}

flutter {
source '../..'
source '../..'
}

dependencies {
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.2.0'
androidTestImplementation 'androidx.test:rules:1.2.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}
Expand Up @@ -6,6 +6,7 @@
<activity
android:name="io.flutter.embedding.android.FlutterActivity"
android:launchMode="singleTop"
android:exported="true"
android:theme="@style/LaunchTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
Expand Down
@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="default_web_client_id" translatable="false">406099696497-a12gakvts4epfk5pkio7dphc1anjiggc.apps.googleusercontent.com</string>
<string name="firebase_database_url" translatable="false">https://flutterfire-e2e-tests-default-rtdb.europe-west1.firebasedatabase.app</string>
<string name="gcm_defaultSenderId" translatable="false">406099696497</string>
<string name="google_api_key" translatable="false">AIzaSyCdRjCVZlhrq72RuEklEyyxYlBRCYhI2Sw</string>
<string name="google_app_id" translatable="false">1:406099696497:android:0d4ed619c031c0ac3574d0</string>
<string name="google_crash_reporting_api_key" translatable="false">AIzaSyCdRjCVZlhrq72RuEklEyyxYlBRCYhI2Sw</string>
<string name="google_storage_bucket" translatable="false">flutterfire-e2e-tests.appspot.com</string>
<string name="project_id" translatable="false">flutterfire-e2e-tests</string>
</resources>
Expand Up @@ -6,7 +6,6 @@ buildscript {

dependencies {
classpath 'com.android.tools.build:gradle:4.1.2'
classpath 'com.google.gms:google-services:4.3.4'
}
}

Expand Down
@@ -1,7 +1,3 @@
org.gradle.jvmargs=-Xmx1536M
android.enableR8=true
android.useAndroidX=true
android.enableJetifier=true
org.gradle.daemon=true
org.gradle.caching=true
org.gradle.parallel=true
Expand Up @@ -3,4 +3,4 @@ distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-all.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-6.7-all.zip
@@ -1,15 +1,11 @@
include ':app'

def flutterProjectRoot = rootProject.projectDir.parentFile.toPath()
def localPropertiesFile = new File(rootProject.projectDir, "local.properties")
def properties = new Properties()

def plugins = new Properties()
def pluginsFile = new File(flutterProjectRoot.toFile(), '.flutter-plugins')
if (pluginsFile.exists()) {
pluginsFile.withReader('UTF-8') { reader -> plugins.load(reader) }
}
assert localPropertiesFile.exists()
localPropertiesFile.withReader("UTF-8") { reader -> properties.load(reader) }

plugins.each { name, path ->
def pluginDirectory = flutterProjectRoot.resolve(path).resolve('android').toFile()
include ":$name"
project(":$name").projectDir = pluginDirectory
}
def flutterSdkPath = properties.getProperty("flutter.sdk")
assert flutterSdkPath != null, "flutter.sdk not set in local.properties"
apply from: "$flutterSdkPath/packages/flutter_tools/gradle/app_plugin_loader.gradle"

This file was deleted.

@@ -0,0 +1,87 @@
// File generated by FlutterFire CLI.
// ignore_for_file: lines_longer_than_80_chars, avoid_classes_with_only_static_members
import 'package:firebase_core/firebase_core.dart' show FirebaseOptions;
import 'package:flutter/foundation.dart'
show defaultTargetPlatform, kIsWeb, TargetPlatform;

/// Default [FirebaseOptions] for use with your Firebase apps.
///
/// Example:
/// ```dart
/// import 'firebase_options.dart';
/// // ...
/// await Firebase.initializeApp(
/// options: DefaultFirebaseOptions.currentPlatform,
/// );
/// ```
class DefaultFirebaseOptions {
static FirebaseOptions get currentPlatform {
if (kIsWeb) {
return web;
}
switch (defaultTargetPlatform) {
case TargetPlatform.android:
return android;
case TargetPlatform.iOS:
return ios;
case TargetPlatform.macOS:
return macos;
default:
throw UnsupportedError(
'DefaultFirebaseOptions are not supported for this platform.',
);
}
}

static const FirebaseOptions web = FirebaseOptions(
apiKey: 'AIzaSyB7wZb2tO1-Fs6GbDADUSTs2Qs3w08Hovw',
appId: '1:406099696497:web:87e25e51afe982cd3574d0',
messagingSenderId: '406099696497',
projectId: 'flutterfire-e2e-tests',
authDomain: 'flutterfire-e2e-tests.firebaseapp.com',
databaseURL:
'https://flutterfire-e2e-tests-default-rtdb.europe-west1.firebasedatabase.app',
storageBucket: 'flutterfire-e2e-tests.appspot.com',
measurementId: 'G-JN95N1JV2E',
);

static const FirebaseOptions android = FirebaseOptions(
apiKey: 'AIzaSyCdRjCVZlhrq72RuEklEyyxYlBRCYhI2Sw',
appId: '1:406099696497:android:0d4ed619c031c0ac3574d0',
messagingSenderId: '406099696497',
projectId: 'flutterfire-e2e-tests',
databaseURL:
'https://flutterfire-e2e-tests-default-rtdb.europe-west1.firebasedatabase.app',
storageBucket: 'flutterfire-e2e-tests.appspot.com',
);

static const FirebaseOptions ios = FirebaseOptions(
apiKey: 'AIzaSyDooSUGSf63Ghq02_iIhtnmwMDs4HlWS6c',
appId: '1:406099696497:ios:acd9c8e17b5e620e3574d0',
messagingSenderId: '406099696497',
projectId: 'flutterfire-e2e-tests',
databaseURL:
'https://flutterfire-e2e-tests-default-rtdb.europe-west1.firebasedatabase.app',
storageBucket: 'flutterfire-e2e-tests.appspot.com',
androidClientId:
'406099696497-tvtvuiqogct1gs1s6lh114jeps7hpjm5.apps.googleusercontent.com',
iosClientId:
'406099696497-taeapvle10rf355ljcvq5dt134mkghmp.apps.googleusercontent.com',
iosBundleId: 'io.flutter.plugins.firebase.tests',
);

static const FirebaseOptions macos = FirebaseOptions(
apiKey: 'AIzaSyDooSUGSf63Ghq02_iIhtnmwMDs4HlWS6c',
appId: '1:406099696497:ios:acd9c8e17b5e620e3574d0',
messagingSenderId: '406099696497',
projectId: 'flutterfire-e2e-tests',
databaseURL:
'https://flutterfire-e2e-tests-default-rtdb.europe-west1.firebasedatabase.app',
storageBucket: 'flutterfire-e2e-tests.appspot.com',
androidClientId:
'406099696497-tvtvuiqogct1gs1s6lh114jeps7hpjm5.apps.googleusercontent.com',
iosClientId:
'406099696497-taeapvle10rf355ljcvq5dt134mkghmp.apps.googleusercontent.com',
iosBundleId: 'io.flutter.plugins.firebase.tests',
);
}

0 comments on commit 30216c4

Please sign in to comment.