Convert Figma logo to code with AI

firebase logofirebase-android-sdk

Firebase Android SDK

2,264
574
2,264
437

Top Related Projects

🔥 A well-tested feature-rich modular Firebase implementation for React Native. Supports both iOS & Android platforms for all Firebase services.

Firebase Javascript SDK

Firebase Admin Python SDK

Firebase Admin Node.js SDK

Parse Server for Node.js / Express

Quick Overview

The firebase/firebase-android-sdk repository contains the official Firebase SDK for Android. It provides a comprehensive set of tools and services for building and scaling mobile applications, including real-time database, authentication, cloud storage, and analytics.

Pros

  • Comprehensive suite of tools for mobile app development
  • Seamless integration with Google Cloud Platform
  • Real-time data synchronization across devices
  • Robust documentation and community support

Cons

  • Potential vendor lock-in with Google services
  • Learning curve for developers new to Firebase
  • Limited customization options for some features
  • Can become costly for large-scale applications

Code Examples

  1. Initialize Firebase in your Android app:
// In your Application class
class MyApplication : Application() {
    override fun onCreate() {
        super.onCreate()
        Firebase.initialize(this)
    }
}
  1. Authenticate a user with email and password:
FirebaseAuth.getInstance().createUserWithEmailAndPassword(email, password)
    .addOnCompleteListener { task ->
        if (task.isSuccessful) {
            // User created successfully
        } else {
            // Handle errors
        }
    }
  1. Write data to Firebase Realtime Database:
val database = Firebase.database
val myRef = database.getReference("message")

myRef.setValue("Hello, Firebase!")
    .addOnSuccessListener {
        // Write was successful
    }
    .addOnFailureListener {
        // Handle errors
    }

Getting Started

  1. Add the Firebase SDK to your project's build.gradle:
dependencies {
    implementation platform('com.google.firebase:firebase-bom:30.0.0')
    implementation 'com.google.firebase:firebase-analytics-ktx'
    // Add other Firebase products as needed
}
  1. Initialize Firebase in your Application class:
class MyApplication : Application() {
    override fun onCreate() {
        super.onCreate()
        Firebase.initialize(this)
    }
}
  1. Use Firebase services in your app:
// Example: Get a reference to the database
val database = Firebase.database
val myRef = database.getReference("message")

// Write a message to the database
myRef.setValue("Hello, Firebase!")

Competitor Comparisons

🔥 A well-tested feature-rich modular Firebase implementation for React Native. Supports both iOS & Android platforms for all Firebase services.

Pros of react-native-firebase

  • Cross-platform support for both iOS and Android
  • Simplified API tailored for React Native development
  • Comprehensive documentation and active community support

Cons of react-native-firebase

  • May lag behind official SDK in terms of new feature implementations
  • Potential for inconsistencies with native Firebase SDKs
  • Additional layer of abstraction may impact performance in some cases

Code Comparison

firebase-android-sdk (Java):

FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("users").document("user1").set(user);

react-native-firebase (JavaScript):

import firestore from '@react-native-firebase/firestore';
firestore().collection('users').doc('user1').set(user);

Summary

firebase-android-sdk is the official Android SDK for Firebase, offering native performance and direct integration with Android apps. It provides the most up-to-date features and is maintained directly by Google.

react-native-firebase is a community-driven project that wraps Firebase SDKs for use in React Native applications. It offers a unified API for both iOS and Android platforms, making it easier for React Native developers to integrate Firebase services into their cross-platform apps.

The choice between these repositories depends on the specific needs of the project, with firebase-android-sdk being ideal for native Android development and react-native-firebase better suited for React Native cross-platform applications.

Firebase Javascript SDK

Pros of firebase-js-sdk

  • Broader platform support, including web browsers and Node.js environments
  • Easier integration with JavaScript-based frameworks and libraries
  • More frequent updates and releases

Cons of firebase-js-sdk

  • Potentially larger bundle size for web applications
  • May require additional setup for certain features compared to native SDKs

Code Comparison

firebase-js-sdk:

import { initializeApp } from 'firebase/app';
import { getFirestore, collection, addDoc } from 'firebase/firestore';

const app = initializeApp(firebaseConfig);
const db = getFirestore(app);

await addDoc(collection(db, 'users'), { name: 'John', age: 30 });

firebase-android-sdk:

import com.google.firebase.firestore.FirebaseFirestore

val db = FirebaseFirestore.getInstance()
val user = hashMapOf("name" to "John", "age" to 30)

db.collection("users").add(user)
    .addOnSuccessListener { documentReference ->
        Log.d(TAG, "Document added with ID: ${documentReference.id}")
    }

Both SDKs provide similar functionality for Firebase services, but with syntax and implementation differences specific to their respective platforms. The JavaScript SDK offers a more modular approach with separate imports, while the Android SDK uses a more object-oriented style with method chaining.

Firebase Admin Python SDK

Pros of firebase-admin-python

  • Easier to use for server-side applications and backend services
  • More suitable for data processing and analytics tasks
  • Supports a wider range of Firebase services on the server-side

Cons of firebase-admin-python

  • Limited to server-side usage, not suitable for client-side Android development
  • Lacks real-time synchronization features available in the Android SDK
  • May have slower performance for mobile-specific tasks compared to the native Android SDK

Code Comparison

firebase-admin-python:

import firebase_admin
from firebase_admin import credentials, firestore

cred = credentials.Certificate("path/to/serviceAccount.json")
firebase_admin.initialize_app(cred)
db = firestore.client()

firebase-android-sdk:

import com.google.firebase.FirebaseApp
import com.google.firebase.firestore.FirebaseFirestore

FirebaseApp.initializeApp(context)
val db = FirebaseFirestore.getInstance()

The firebase-admin-python SDK is designed for server-side applications, offering a broader range of Firebase services and easier integration with backend systems. It excels in data processing and analytics tasks. However, it lacks the real-time synchronization features and mobile-specific optimizations found in the firebase-android-sdk. The Android SDK is tailored for client-side development on Android devices, providing better performance for mobile-specific tasks but with a more limited scope of server-side operations.

Firebase Admin Node.js SDK

Pros of firebase-admin-node

  • Supports server-side operations and admin-level access to Firebase services
  • Provides a more flexible and powerful API for backend development
  • Can be used in various Node.js environments, including cloud functions and servers

Cons of firebase-admin-node

  • Limited to server-side usage, not suitable for client-side applications
  • Requires more setup and configuration compared to the Android SDK
  • May have a steeper learning curve for developers new to Node.js

Code Comparison

firebase-admin-node:

const admin = require('firebase-admin');
admin.initializeApp();
const db = admin.firestore();
const docRef = db.collection('users').doc('userId');
await docRef.set({ name: 'John Doe', age: 30 });

firebase-android-sdk:

val db = FirebaseFirestore.getInstance()
val user = hashMapOf("name" to "John Doe", "age" to 30)
db.collection("users").document("userId")
    .set(user)
    .addOnSuccessListener { /* ... */ }
    .addOnFailureListener { /* ... */ }

The firebase-admin-node code uses Node.js and provides a more straightforward async/await syntax, while the firebase-android-sdk code is in Kotlin and uses a callback-based approach typical for Android development. The admin SDK offers more direct access to Firebase services, while the Android SDK is optimized for mobile app integration.

Parse Server for Node.js / Express

Pros of Parse Server

  • Open-source and self-hostable, offering more control and customization
  • Platform-agnostic, supporting multiple programming languages and platforms
  • More flexible and extensible through plugins and custom cloud code

Cons of Parse Server

  • Requires more setup and maintenance compared to Firebase's managed service
  • Smaller ecosystem and community support
  • May have higher operational costs for scaling and infrastructure management

Code Comparison

Parse Server (JavaScript):

const express = require('express');
const ParseServer = require('parse-server').ParseServer;
const app = express();
const api = new ParseServer({
  databaseURI: 'mongodb://localhost:27017/dev',
  appId: 'myAppId',
  masterKey: 'myMasterKey',
  serverURL: 'http://localhost:1337/parse'
});
app.use('/parse', api);

Firebase Android SDK (Kotlin):

import com.google.firebase.FirebaseApp
import com.google.firebase.firestore.FirebaseFirestore

FirebaseApp.initializeApp(this)
val db = FirebaseFirestore.getInstance()
val docRef = db.collection("users").document("alovelace")

Both repositories offer robust backend solutions for mobile and web applications. Parse Server provides more flexibility and control but requires more setup, while Firebase Android SDK offers a managed service with easier integration but less customization options. The choice between them depends on specific project requirements, development resources, and scalability needs.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Firebase Android Open Source Development

This repository contains the source code for all Android Firebase SDKs except Analytics and Auth.

Firebase is an app development platform with tools to help you build, grow and monetize your app. More information about Firebase can be found at https://firebase.google.com.

Table of contents

  1. Getting Started
  2. Testing
    1. Unit Testing
    2. Integration Testing
  3. Proguarding
    1. APIs used via reflection
    2. APIs intended for developer consumption
    3. APIs intended for other Firebase SDKs
  4. Publishing
    1. Dependencies
    2. Commands
  5. Code Formatting
  6. Contributing

Getting Started

  • Install the latest Android Studio (should be 3.0.1 or later)
  • Clone the repo (git clone --recurse-submodules git@github.com:firebase/firebase-android-sdk.git)
    • When cloning the repo, it is important to get the submodules as well. If you have already cloned the repo without the submodules, you can update the submodules by running git submodule update --init --recursive.
  • Import the firebase-android-sdk gradle project into Android Studio using the Import project(Gradle, Eclipse ADT, etc.) option.
  • firebase-crashlytics-ndk must be built with NDK 21. See firebase-crashlytics-ndk for more details.

Testing

Firebase Android libraries exercise all three types of tests recommended by the Android Testing Pyramid. Depending on the requirements of the specific project, some or all of these tests may be used to support changes.

:warning: Running tests with errorprone

To run with errorprone add withErrorProne to the command line, e.g.

./gradlew :<firebase-project>:check withErrorProne.

Unit Testing

These are tests that run on your machine's local Java Virtual Machine (JVM). At runtime, these tests are executed against a modified version of android.jar where all final modifiers have been stripped off. This lets us sandbox behaviors at desired places and use popular mocking libraries.

Unit tests can be executed on the command line by running

./gradlew :<firebase-project>:check

Vertex AI for Firebase

See the Vertex AI for Firebase README for setup instructions specific to that project.

Integration Testing

These are tests that run on a hardware device or emulator. These tests have access to Instrumentation APIs, give you access to information such as the Android Context. In Firebase, instrumentation tests are used at different capacities by different projects. Some tests may exercise device capabilities, while stubbing any calls to the backend, while some others may call out to nightly backend builds to ensure distributed API compatibility.

Along with Espresso, they are also used to test projects that have UI components.

Project Setup

Before you can run integration tests, you need to add a google-services.json file to the root of your checkout. You can use the google-services.json from any project that includes an Android App, though you'll likely want one that's separate from any production data you have because our tests write random data.

If you don't have a suitable testing project already:

  • Open the Firebase console
  • If you don't yet have a project you want to use for testing, create one.
  • Add an Android app to the project
  • Give the app any package name you like.
  • Download the resulting google-services.json file and put it in the root of your checkout.

Running Integration Tests on Local Emulator

Integration tests can be executed on the command line by running

./gradlew :<firebase-project>:connectedCheck

Running Integration Tests on Firebase Test Lab

You need additional setup for this to work:

  • gcloud needs to be installed on local machine
  • gcloud needs to be configured with a project that has billing enabled
  • gcloud needs to be authenticated with credentials that have 'Firebase Test Lab Admin' role

Integration tests can be executed on the command line by running

./gradlew :<firebase-project>:deviceCheck

This will execute tests on devices that are configured per project, if nothing is configured for the project, the tests will run on model=panther,version=33,locale=en,orientation=portrait.

Projects can be configured in the following way:

firebaseTestLab {
  // to get a list of available devices execute `gcloud firebase test android models list`
  devices = [
    '<device1>',
    '<device2>',
  ]
}

Annotations

Firebase SDKs use some special annotations for tooling purposes.

@Keep

APIs that need to be preserved up until the app's runtime can be annotated with @Keep. The @Keep annotation is blessed to be honored by android's default proguard configuration. A common use for this annotation is because of reflection. These APIs should be generally discouraged, because they can't be proguarded.

@KeepForSdk

APIs that are intended to be used by Firebase SDKs should be annotated with @KeepForSdk. The key benefit here is that the annotation is blessed to throw linter errors on Android Studio if used by the developer from a non firebase package, thereby providing a valuable guard rail.

@PublicApi

We annotate APIs that meant to be used by developers with @PublicAPI. This annotation will be used by tooling to help inform the version bump (major, minor, patch) that is required for the next release.

Proguarding

Firebase SDKs do not proguard themselves, but support proguarding. Firebase SDKs themselves are proguard friendly, but the dependencies of Firebase SDKs may not be.

Proguard config

In addition to preguard.txt, projects declare an additional set of proguard rules in a proguard.txt that are honored by the developer's app while building the app's proguarded apk. This file typically contains the keep rules that need to be honored during the app' s proguarding phase.

As a best practice, these explicit rules should be scoped to only libraries whose source code is outside the firebase-android-sdk codebase making annotation based approaches insufficient.The combination of keep rules resulting from the annotations, the preguard.txt and the proguard.txt collectively determine the APIs that are preserved at runtime.

Publishing

Firebase is published as a collection of libraries each of which either represents a top level product, or contains shared functionality used by one or more projects. The projects are published as managed maven artifacts available at Google's Maven Repository. This section helps reason about how developers may make changes to firebase projects and have their apps depend on the modified versions of Firebase.

Dependencies

Any dependencies, within the projects, or outside of Firebase are encoded as maven dependencies into the pom file that accompanies the published artifact. This allows the developer's build system (typically Gradle) to build a dependency graph and select the dependencies using its own resolution strategy

Commands

For more advanced use cases where developers wish to make changes to a project, but have transitive dependencies point to publicly released versions, individual projects may be published as follows.

# e.g. to publish Firestore and Functions
./gradlew -PprojectsToPublish="firebase-firestore,firebase-functions" \
    publishReleasingLibrariesToMavenLocal

Developers may take a dependency on these locally published versions by adding the mavenLocal() repository to your repositories block in your app module's build.gradle.

Code Formatting

Java and Kotlin are both formatted using spotless.

To run formatting on a project, run

./gradlew :<firebase-project>:spotlessApply

Contributing

We love contributions! Please read our contribution guidelines to get started.