CODEX
Complete Guide on Sending Push Notifications on Android - Using Firebase
Holla! 👋, I will explain how to send push notifications on android using Firebase Cloud Messaging
.
Push notifications are messages that pop up on a users device. A user can see these notifications without having to be on the app. This is important for users retention.
WHAT WE ARE BUILDING
We are simply going to build an app that lets a user input a message and send a push notification to that user containing that message. Simple! 😄
This is how the final app will look like
OnClick of that button
- Push Notification is sent to the user which contains the message you inputted
Technologies Used
- Firebase (Cloud Messaging)
- Kotlin (For Android)
- NodeJS (Backend)
- Android Studio IDE
STEPS
- Set up android studio
- Set up firebase project
- Add dependencies
- Set up Hilt And Retrofit
- Set Up Firebase Cloud Messaging
- Build view
- Setup Repository ViewModel and View
- Set up our backend with NodeJS
Alright, lets see each of them, one by one
SET UP ANDROID STUDIO
Create Project
- First download android studio and install.
- Create A New Project — Choose
Empty Activity
- Name your project anything, I named mine
Firebase Notification Android
- Click
Finish
Structure Project
We are using MVVM architectural pattern for this project
- Create 7
new packages
name them —di
,firebase
,helper
,model
,view
,viewmodel
,network
- Move
MainActivity
to theview
package
SETUP FIREBASE PROJECT
- Go to https://console.firebase.google.com/
- Sign in and click on
Add Project
- Enter the name of your project — Name it anything,
- Click
Continue
- On the Google Analytics page, Click
Continue
- Choose a Google Account — Select
Default Account For Firebase
- Click
Create Project
- You will see — “
Your new project is ready
” - Click
Continue
Congrats, you have successfully created a firebase project. Now, lets link the project with our android app
Connecting Firebase With Android
- On your console home page click on the Android Logo
- Android Package Name — Go to your
Manifest.xml
, copy thepackage
and paste it there, it should be something like this —com.name.firebasenotificationandroid
- App Nickname — Put anything there
- Debug Signing Certificate — Go to
Android Studio
, Click ongradle
—Tasks
—Android
—signingReport
- Copy the SHA-1 key and paste
- Click on
Register App
- Download
google-services.json
and paste in youproject
folderapp directory
- Add all the necessary firebase dependencies
- Sync project and you are done 👏
ADD DEPENDENCIES
This app makes use of coroutines, hilt, retrofit, cloud messaging etc.
- Open your
build.gradle(app)
file and add them
Open build.gradle(project)
add hilt class path
.........dependencies {
........ //firebase
classpath 'com.google.gms:google-services:4.3.4'
//hilt
classpath 'com.google.dagger:hilt-android-gradle-plugin:2.28-alpha'
}
............
HILT
- Create 2 new class under
di
package name them —AppModule
andMyApplication
- AppModule — This class is used to perform injection to types such as interfaces and classes from external libraries which we do not own e.g Retrofit.
- MyApplication — This class extends Application class. This will generate all the needed hilt codes and serve as a dependency container. It should look like this.
//Make sure you add this
@HiltAndroidApp
class MyApplication: Application() {
}
- Finally, go to your Manifest.xml file, in the
application
tag addandroid:name=”.di.MyApplication”
RETROFIT
- Under
helper
package, create a class calledEndPoints
EndPoints — A class where our base url and all api calls endpoint resides
class EndPoints {
companion object {
//BASE
const val BASE_URL = "https://put-your-base-url-here/"
//SAVE_TOKEN
const val SAVE_TOKEN = "save"
}
}
- Under
model
package, create a class nameAuthResponse
AuthResponse — A class that models the response gotten from the server so we can take proper action
data class AuthResponse(
val message: String,
val status: String
)
- Under the
network
package, create aninterface
calledApiService
and 2 new classes, name them —ApiDataSource
,BaseDataSource
ApiService - An interface
where we will make a Post Request
to our server to save a user’s name and notification token.
ApiDataSource- A class that exposes the ApiService
so that we can use it in our repository
We are done with retrofit and hilt.
SET UP FIREBASE CLOUD MESSAGING
- Under
firebase
package, create a new class - MyFirebaseMessagingService — This class extendsFirebaseMessagingService
that handles messages, recieving notifications in foreground, receiving data payload, sending up stream messages
- Under
helper
create anobject
—Utility
Utility — A utility class with a function that builds our notification — Handling stuffs such as — action when a user taps on the notification, customizing look of notification e.t.c
- Open
Manifest.xlm
, before the closing application tag, add this
<service
android:name=".firebase.MyFirebaseMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
...
</application>
- Add a default notification icon,color and channel, add to
manifest.xml
within theapplication
tag
<meta-data android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="@drawable/ic_bell" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="@color/colorAccent" /><meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="@string/default_notification_channel_id" />
That should be all for configuring cloud messaging
Build View/Layout
Open main_activity.xml
and use this code
Okay, now we have our not so beautiful view and everything set up, now lets set up our repository and viewmodel.
Setup Repository, ViewModel and View
- Open
viewmodel
package, create 2 new classes —MainRepo
andMainViewModel
MainRepo — This class serves as a source of data for our viewModel to consume.
MainViewModel — This class communicates with the repository, the result from the api call is then returned as a LiveData (Lifecycle aware) which is then observed by our view (MainActivity)
- Open
MainActivity
Here’s what this class does
- Get the views through ViewBinding
- Initialize the views
- Listen to click even on the button
- Communicate with viewModel to register the user
- Observe the data from the viewModel and display appropriate messages
SET UP NODEJS BACKEND
- Go to your firebase console, click
settings icon
->Project settings
- Switch to
Service Account
tab, ClickGenerate new private key
- Confirm and download it
- Now create a folder in your pc, navigate to that folder with your terminal
npm init
and fill in all required details. This will create a package.json filenpm i firebase-admin
on your terminal to install firebase dependency- Also
npm i express
andnpm i bodyparser
- Create a config file
- Create index.js file
Okay, we are done. Take a deep breath! 😫
This is a link to the complete project, please check it out
You can go further by first storing the notification token against a user in your users table to target a particular user.
Also, notifications can be sent to a group of users using “topic”
Thank you!
Reach Me