What is Firebase? Serverless for mobile developers

Most mobile developers working on an app are likely to encounter a common problem: how to write backend services. Achieving a solid architecture that allows the service to scale correctly (with minimal downtime) requires solid knowledge in backend technologies. Without it, you’re likely to waste a lot of time and money.
Mobile backend as a Service (MBaaS) has been a real lifesaver for the mobile developer. With MBaaS, a developer can take a few lines of code and some tuning and use services like realtime database, storage, and authentication without having to know how they work. In this post, I’d like to answer the question ‘What is Firebase?,  the platform that solved my mobile app development issues. Today, I’ll walk you through an overview of the platform and show you how to use it to create a useable mobile chat app.

What is Firebase?

Firebase is mobile and web application development platform. According to Wikipedia, the initial Firebase product was a “realtime database, which provides an API that allows developers to store and sync data across multiple clients.” The company was founded in 2011 by Andrew Lee and James Tamplin and acquired by Google in 2014. In 2016, Firebase announced that it was “expanding to become a unified app platform for Android, iOS, and mobile web development.”
Currently, Firebase is an all-encompassing product that has everything I needed to develop the app (storage, authorization, realtime database, and push notification system). For the purposes of my project, I will combine these services to create a usable chat application that is ready to scale based on users.

What is a real-time database?

A real-time database is a schemaless database in which the data is stored in JSON format. It is optimized for offline use due to the persistence of local data on the device and automatically synchronizes from SDK. By default, only authenticated users have read/write access but this can be made public through the configuration.

Step 1: Configure project

To add the Firebase database, you have to insert your Android App project into the Gradle file:

compile 'com.google.firebase:firebase-database:10.0.1'

Step 2: Write data

With the API offered from SDK, you can easily write into the database:

// Write a message to the database
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("message");
myRef.setValue("Hello, World!");

Step 3: Read data

A Firebase Database is different from a common SQL database. To access the data written inside the Firebase database, it has to “listen” to the key we want to read and which must be notified of the changes. This is the key part of this tool: the real-time communication of data. This opens up a wide range of applications that (like chat apps), using common databases, we should implement from scratch with different tools and work hour. 

myRef.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        // This method is called once with the initial value and again
        // whenever data at this location is updated.
        String value = dataSnapshot.getValue(String.class);
        Log.d(TAG, "Value is: " + value);
    }
    @Override
    public void onCancelled(DatabaseError error) {
        // Failed to read value
        Log.w(TAG, "Failed to read value.", error.toException());
    }
});

 

Authentication

With a little effort, we will have a tool for identifying and storing users with all of the major OAuth systems available today.

Step 1: Configure project

In order to add the Firebase Auth, you have to insert the following into the Gradle file of your Android App project:

compile 'com.google.firebase:firebase-auth:10.0.1'

Step 2: Enable provider

Step 3: Add code to our application

Next, with a few lines of code, you will have successfully added a registration with user and email into the app, without touching anything:

mAuth.createUserWithEmailAndPassword(email, password)
        .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                Log.d(TAG, "createUserWithEmail:onComplete:" + task.isSuccessful());
                // If sign in fails, display a message to the user. If sign in succeeds
                // the auth state listener will be notified and logic to handle the
                // signed in user can be handled in the listener.
                if (!task.isSuccessful()) {
                    Toast.makeText(EmailPasswordActivity.this, R.string.auth_failed,
                            Toast.LENGTH_SHORT).show();
                }
                // ...
            }
        });

Step 4: View registered users

In the Firebase console, you can see all of the users registered through the implementation of our application. Another useful feature is the email template, which enables communication with the user, such as for sending an email confirmation after registration.

Storage

Firebase will easily allow us to upload and download the files we will use in chat. Like other services, this includes the SDK and rules for content visibility:

Step 1: Configure project

To add the Firebase storage, you will need to insert the following into the Gradle file of your Android App project:

'com.google.firebase:firebase-storage:10.0.1'

Step 2: Upload a file

You can easily upload a file into the bucket of Firebase storage:

Uri file = Uri.fromFile(new File("path/to/images/rivers.jpg"));
StorageReference riversRef = storageRef.child("images/rivers.jpg");
riversRef.putFile(file)
    .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
            // Get a URL to the uploaded content
            Uri downloadUrl = taskSnapshot.getDownloadUrl();
        }
    })
    .addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception exception) {
            // Handle unsuccessful uploads
            // ...
        }
    });

The implementation of this API also offers the pause/resume function that is very useful in developing mobile applications due to an inconsistent internet connection.

Step 3: Download a file

File localFile = File.createTempFile("images", "jpg");
riversRef.getFile(localFile)
    .addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
        @Override
        public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
            // Successfully downloaded data to local file
            // ...
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception exception) {
            // Handle failed download
            // ...
        }
    });

Firebase Cloud Messaging

Firebase Cloud Messaging is a multi-platform push notification system that allows us to send messages both via the web platform made available by Firebase or through integration with other services that trigger a push (Google Cloud Functions).

Cloud Functions for Firebase

This is, in my opinion, is one of the best features of Firebase. Cloud Functions for Firebase allows you to “automatically run backend code in response to events triggered by Firebase features and HTTPS requests.” Essentially, it is a piece of code that runs something like “create a thumbnail of an image,” which alone is not very useful, however, you can attach it to the Firebase Storage and set the trigger for calling this function after an image is uploaded to it. After that, the function executes the following steps:

  1. Get the original image
  2. Convert it into a thumbnail
  3. Write the new filename with location to the database
  4. Upload the new image to storage
  5. Now, the app sees the thumbnail

Other ways that Cloud Functions can be used:

Third-party integration

You can also use the Cloud Function with other systems, such as GitHub or Slack, that allow you integrate it into your project. However, this is not included in Firebase’s Free Plan.

Pricing

Usually at this point comes the painful side note, i.e. the price. But for our experiment today, the cost will be 0 as you can see from the table below:

 Conclusion

After exploring the Firebase platform a bit, I can say that it was exactly what I was looking for. It includes everything that my application might need without having to distract too much from the overall mobile development.
Developing this just a few years ago would have been a much different story. Putting together an archive to run photos, a database that would notify me of changes in real time, and a user management system will all the possible integrations plus email confirmation with a customizable template would have required many working hours.
Any service that allows me to focus on the overall idea behind what we’re developing (and less on some of the more technical bits) will definitely have my attention going forward.

Written by

Giacomo is a passionate mobile developer, he started hacking with the “mobile world” since his childhood…If other children were asking parents for a new game he dreamed of receiving a Nokia communicator for his birthday! After few years as a Backend developer, he caught the opportunity to work on B2B tailored projects for BlackBerry Device. Now he builds Android apps focusing on the architecture. He loves food, tv series, anime and a lot of other geek’s stuff

Related Posts

— January 23, 2018

Latest Updates for Cloud Academy Mobile: New Content Library

At Cloud Academy, we want to make learning on the go as easy as possible. In our newest update, we are further unifying the user experience between web and mobile.Today, with an overall faster app launch speed and our new content library for iOS and Android, you’ll be able to get to t...

Read more
  • Mobile
  • Product Feature
— June 21, 2017

Introducing the New Cloud Academy Mobile App

Following on our recent updates to the Cloud Academy web interface, today, we’re happy to announce that we’ve implemented many of these same changes on our mobile app for both iOS and Android.New features of the Cloud Academy mobile appUIYou may have already noticed that our mobil...

Read more
  • Android
  • AWS
  • Cloud Computing
  • iOS
  • Mobile
— April 4, 2017

Mobile testing with AWS: Using AWS Device Farm

AWS Device Farm is a testing service for mobile app developers using Android, iOS, or Amazon Fire OS apps. Announced at the regional AWS Summit in New York City in July 2015, AWS Device Farm allows developers to simultaneously test applications on a wide range of devices including smart...

Read more
  • AWS
  • Mobile
— October 22, 2015

Amazon Cognito: managing mobile account data

Amazon Cognito allows secure authentication in a world where mobile apps are regularly being accessed by individuals using multiple smart devicesAmazon Cognito is an Amazon Web Service that offers mobile identity management and data synchronization across devices. We'll first take som...

Read more
  • AWS
  • Mobile
— October 8, 2015

AWS Mobile Hub

AWS Mobile Hub: the fastest way to build mobile apps on AWSThis morning at re:Invent 2015 in Vegas, Werner Vogels announced the launch of a new service for mobile developers: AWS Mobile Hub.During the last year AWS has announced and released many services to ease the management of m...

Read more
  • AWS
  • Mobile
— June 6, 2014

Multiple identities on AWS Management Console Mobile App

If you are a user of Amazon Web Services, you probably know very well the AWS Management Console: it's the main dashboard your manage your cloud infrastructure from. Nevertheless, chances are that you don't know there is an equivalent app available for Android and iOS to achieve the ver...

Read more
  • AWS
  • Mobile