Why firebase is the best as a Mobile Application backend?

Firebase for Mobile Application, By using Firebase we can be created quickly powerful and scalable application and the best thing is we do not worry about server end, everything is managed by firebase itself.we do not need to call API and managed databases so half of the work is done by firebase. It is fully managed platform to develop Ios Application, Android Application, and Web Application. It is fully filled with the feature. Firebase is different from Google Service Platform.  Since Google I/O 2016 there have been some major updates to Firebase. Below is information related to the legacy service.

Some Feature of Firebase :

1>Authentication: Firebase Authentication provides backend services for the mobile application.t supports authentication using passwords, phone numbers, social networking identity providers like Google, Facebook and Twitter, and more. we do not need server API firebase authentication provides security. For firebase Auth we need to add dependencies :

implementation 'com.google.firebase:firebase-auth:11.8.0'
For example we see login with mobile number and verify OTP with firebase:
FirebaseAuth auth ;
Firest initialize fiebase Auth in onCreate() method:
auth = FirebaseAuth.getInstance();

and then

String phone = mobile_editText.getText().toString();

private void sendVerificationCode(String phoneNumber, PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks) {
    PhoneAuthProvider.getInstance().verifyPhoneNumber(
            "+91" + phoneNumber,        // Phone number to verify
            60,                 // Timeout duration
            TimeUnit.SECONDS,   // Unit of timeout
            Signup_Activity.this,               // Activity (for callback binding)
            mCallbacks);        // OnVerificationStateChangedCallbacks
}

PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
    @Override
    public void onVerificationCompleted(PhoneAuthCredential credential) {

        Log.d(TAG, "onVerificationCompleted:" + credential);
        _credential = credential;
        if (_credential.getSmsCode() != null) {
            otp_editText.setText(_credential.getSmsCode());
            submitMethodCalled();
        } else {
            signInWithPhoneAuthCredential(credential);

        }
    }

    @Override
    public void onVerificationFailed(FirebaseException e) {

        Log.w(TAG, "onVerificationFailed", e);

        Singleton.hideLoader();
        if (e instanceof FirebaseAuthInvalidCredentialsException) {
            // Invalid request
            verification_text.setVisibility(View.VISIBLE);
            verification_text.setText(e.getLocalizedMessage());
            verification_text.setTextColor(getResources().getColor(R.color.green));

        } else if (e instanceof FirebaseTooManyRequestsException) {
            // The SMS quota for the project has been exceeded
            verification_text.setVisibility(View.VISIBLE);
            verification_text.setText("SMS quota for the project has been exceeded");
            verification_text.setTextColor(getResources().getColor(R.color.green));
        }


    }

    @Override
    public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
        super.onCodeSent(s, forceResendingToken);

        codesent = s;
        verification_text.setText("Verification code has been sent");
        otp_editText.setText("");
    }
};


private void submitMethodCalled() {

    if (_credential != null)
        signInWithPhoneAuthCredential(_credential);
    else {

        String code = otp_editText.getText().toString();
        // [START verify_with_code]
        _credential = PhoneAuthProvider.getCredential(codesent, code);
        // [END verify_with_code]

        signInWithPhoneAuthCredential(_credential);
    }
}

private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
    mAuth.signInWithCredential(credential)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {
                     Toast.makeText(getApplicationContext(), "your verification code is valid", Toast.LENGTH_LONG).show();
                     //do own codewhich you want to do on login success

 } else {
 if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
 
 Toast.makeText(getApplicationContext(), "your verification code is invalid", Toast.LENGTH_LONG).show();
 }
 }
 }
 });
}

2>Hosting: Firebase Hosting provides static content hosting.Firebase Hosting is production-grade App content hosting for developers.with using firebase hosting we can create quickly and easily develop the mobile application. Firebase hosting develope modern mobile application. Hosting gives your project a subdomain on the domainfirebaseapp.com. Firebase Hosting offers lightweight configuration options for you to build sophisticated Progressive Web Apps. You can easily rewrite URLs for client-side routing or set up custom headers.

3>Real Time Database: Real-time Database instance and automatically receive updates with the newest data. The Realtime Database provides a flexible, expression-based rules language, called Firebase Real-time Database Security Rules, to define how your data should be structured and when data can be read from or written to. When integrated with Firebase Authentication, developers can define who has access to what data, and how they can access it.

4>Cloud Messaging: Firebase cloud messaging from Google gives an ability to send and receive messages from the client, It is a cross-platform system and it is completely free and it has no limitations. Messages and notifications can be sent to the client app using the app server or the Firebase notifications console. To send push notification in mobile application use firebase cloud messaging.

To send Firebase Cloud Messaging in your app by two types:

i>Notification Message: In Notification messages type of messages are automatically displayed to end user.

ii>Data Message: In Notification messages type of messages is automatically displayed to end user.

To receive these messages in MyFirebaseMessagingService class file on:

@Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        if (remoteMessage.getData().size()>0) {

            String title = remoteMessage.getData().get("title");
            Intent intent = new Intent(Config.PUSH_NOTIFICATION);
            intent.putExtra("title", title);

            LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(this);
            localBroadcastManager.sendBroadcast(intent);

        }
And write below code in your class file: 
private BroadcastReceiver mHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
   //To initialize broadcastReceiver in your activity
    LocalBroadcastManager.getInstance(this).registerReceiver(mHandler, new IntentFilter("your package name"))
    setContentView(R.layout.activity_main);
}
And then below code is add in onCreate() where you want to show messages and count of messages
//To receive notification in foreground where you want to show messages
mHandler = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(PUSH_NOTIFICATION)) {
            // new push notification is received
            String message = intent.getStringExtra("message");
            showReceiveMessageDialog(message);
        }
    }
};
To receive messages when app is in foreground:
//push notification in background
if (getIntent().getExtras() != null) {
    String message = getIntent().getExtras().getString("message");
    showReceiveMessageDialog(message);
}
write this code in your activity class file where you want to receive messages:
 @Override
 protected void onResume() {
 super.onResume();

 // register new push message receiver
 // by doing this, the activity will be notified each time a new message arrives
 LocalBroadcastManager.getInstance(this).registerReceiver(mHandler,
 new IntentFilter(PUSH_NOTIFICATION));

 // clear the notification area when the app is opened
 NotificationUtils.clearNotifications(getApplicationContext());
 }

 @Override
 protected void onPause() {
 LocalBroadcastManager.getInstance(this).unregisterReceiver(mHandler);
 super.onPause();
 }

And please add services in your Manifest file to receive push notification from firebase.

Add Firebase to your application
  • Create an account on Firebase.
  • Create a project in Firebase console.
  • Click Firebase for Android app and follow the instructions.
  • When prompted, enter app’s package name.
  • Download google-services.json file.
  • Place google-services.json file in your app’s module folder. Typically /app.

 

Add  dependencies on your app

dependencies {

classpath ‘com.android.tools.build:gradle:2.2.0-rc1’

classpath ‘com.google.gms:google-services:3.0.0’

}

To Add Firebase messaging dependency

dependencies {

compile ‘com.google.firebase:firebase-messaging:9.6.0’

}

apply plugin: ‘com.google.gms.google-services’

 

Conclusion: Firebase plays the vital role in the development of mobile application in IOS and ANDROID mobile. By using firebase you can manage data from firebase to send the notification, store real-time database, it manages half of the work itself.

 

One Comment

Leave a Reply

Your email address will not be published. Required fields are marked *