Mobile App Development

Sending Push Notification to Mobile Devices using Python with Firebase

Sending Push Notification to Mobile Devices using Python with Firebase

Introduction

In the fast-paced digital age, keeping users engaged with your mobile app is more challenging than ever. With countless apps vying for attention, how can you ensure that your app remains relevant and continues to capture user interest? Enter push notifications—a powerful tool to enhance user engagement and retention.

What Are Push Notifications?

Push notifications are short messages or alerts that mobile apps send to users’ devices, even when the apps are not actively in use. These notifications appear on the device’s lock screen, notification center, or in the banners, and they serve various purposes, such as providing updates, reminders, promotions, or important information.

Push Notification

Importance of push notifications for mobile apps:

  1. Engagement and Retention: Push notifications help keep users engaged with your app by providing timely and relevant information. They can remind users about new features, prompt them to take action, or bring them back to the app if it has been a while since they last used it. By staying top-of-mind, push notifications can increase user retention.
  2. Communication Channel: Push notifications are a direct communication channel between the app and its users. They allow app developers to reach users instantly with important announcements, updates, or personalized messages. This direct line of communication can be invaluable for delivering time-sensitive information or driving user actions.
  3. Personalization and Targeting: Push notifications can be personalized based on user preferences, behavior, or location. By segmenting users and sending targeted messages, app developers can deliver more relevant content to each user, increasing the chances of engagement and conversion. Personalized notifications can enhance the user experience and strengthen user-app relationships.
  4. Promotions and Marketing: Push notifications can promote new products, services, or special offers to users. Whether a limited-time discount, a new feature announcement, or a personalized recommendation, push notifications can drive traffic to specific app features or encourage users to purchase. They are a powerful marketing tool for app developers to increase sales and revenue.
  5. Information and Updates: Push notifications keep users informed about important updates, news, or events related to the app. Whether it’s a software update, a change in terms of service, or a security alert, push notifications ensure that users are always aware of relevant information that affects their app experience.
  6. Enhanced User Experience: When used appropriately, push notifications can enhance the overall user experience by providing valuable information, timely reminders, and personalized interactions. They can help users stay organized, motivated, and engaged with the app, leading to a more positive user experience and higher satisfaction levels.

Prerequisites

List the prerequisites needed for following the tutorial:

Step 1: Set Up :

   1. Dependencies: Need to add below dependencies.

  • For npm –
npm install --save react-native-push-notification
view raw Shell Script hosted with ❤ by GitHub
  • For yarn –
yarn add react-native-push-notification
view raw Shell Script hosted with ❤ by GitHub

2. Firebase setup: To register your Android application in the Firebase dashboard, follow these steps:

  • Register the Android application and give it a name.
  • Select your project or create a new one if you haven’t already.
Push Notification on Mobile
  • Click on the “Add app” button to add a new platform to your project.
Push Notification Add App
  • Choose the Android platform by clicking on the Android icon.
Push Notification Platform
  • Enter your Android app’s package name. This can typically be found in the “android/app/build.gradle” file of your React Native project.
  • (Optional) Enter other optional details such as app nickname and debug signing certificate SHA-1.
  • Click on the “Register app” button to complete the registration process.

[ Tip: To get SHA-1 or SHA-256 certificate go to your project in cmd and then type the following command]

cd android
./gradlew signingReport
view raw Shell Script hosted with ❤ by GitHub
  • After downloading the google-services.json file from the Firebase console, ensure you place it in the root directory of your application module.

3. Android-side Setup: incorporate the necessary code provided by Firebase documentation into the project-level build.gradle file (located at <project>/build.gradle). 

This code snippet configures your project to work with Firebase services.

buildscript {
ext {
...
buildToolsVersion = "34.0.0"
minSdkVersion = 21
compileSdkVersion = 34
targetSdkVersion = 34
ndkVersion = "25.1.8937393"
kotlinVersion = "1.8.0"
...
}
repositories {
...
google() // Add this line
mavenCentral()
...
}
dependencies {
...
classpath("com.google.gms:google-services:4.4.0") // Google Service Plugin
...
}
}
view raw .sh hosted with ❤ by GitHub

apply plugin: “com.facebook.react.rootproject”

After completing the project-level configuration, proceed to create the application-level build.gradle file located at <project>/<app-module>/build.gradle.

apply plugin: “com.google.gms.google-services”


dependencies {

implementation(platform(“com.google.firebase:firebase-bom:32.7.1”))

}

To incorporate Push Notifications into your React Native Android application, replace the following code snippet to your AndroidManifest.xml file.

<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
// Permission for requesting Notification Access
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
<application
android:name=".MainApplication"
android:label="@string/app_name"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:allowBackup="false"
android:theme="@style/AppTheme">
<meta-data android:name="com.dieam.reactnativepushnotification.notification_foreground"
android:value="true" />
<meta-data android:name="com.dieam.reactnativepushnotification.channel_create_default"
android:value="true" />
<meta-data android:name="com.dieam.reactnativepushnotification.notification_color"
android:resource="@color/white" />
<receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationActions"
android:exported="true" />
<receiver
android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationPublisher"
android:exported="true" />
<receiver
android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationBootEventReceiver"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
<action android:name="com.htc.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
</receiver>
<service
android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationListenerService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|screenSize|smallestScreenSize|uiMode"
android:launchMode="singleTask"
android:windowSoftInputMode="adjustResize"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
view raw .xml hosted with ❤ by GitHub

code for dynamic push notifications in React native code component-

import messaging from '@react-native-firebase/messaging';
import { request, PERMISSIONS } from 'react-native-permissions';
//Check Permissions
const checkApplicationPermission = async () => {
request(
PERMISSIONS.ANDROID.POST_NOTIFICATIONS, PERMISSIONS.IOS.POST_NOTIFICATIONS)
.then((statuses) => {
// console.log(statuses[PERMISSIONS.POST_NOTIFICATIONS])
if (statuses[PERMISSIONS.POST_NOTIFICATIONS] === 'granted') {
console.log('Permission granted');
} else {
console.log('Permission already accepted.');
}
})
}
//Message Notification
async function requestUserPermission() {
const authStatus = await messaging().requestPermission();
const enabled =
authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
authStatus === messaging.AuthorizationStatus.PROVISIONAL;
if (enabled) {
console.log('Authorization status:', authStatus);
}
}
useEffect(() => {
(async () => await messaging().registerDeviceForRemoteMessages())();
const unsubscribe = messaging().onMessage(async remoteMessage => {
// On Foreground
Alert.alert(
'New Message',
remoteMessage.notification.title,
[
{
text: 'Open',
onPress: () => {
navigation.dispatch(
CommonActions.navigate({
name: 'ComponentName',
}))
}
},
{
text: 'CLOSE',
onPress: () => {},
},
],
{ cancelable: false }
);
});
//Background Notification
messaging().onNotificationOpenedApp(remoteMessage => {
console.log(
'outApplication',
remoteMessage,
);
navigation.dispatch(
CommonActions.navigate({
name: 'ComponentName',
}))
});
messaging().getInitialNotification()
.then(remoteMessage => {
});
return unsubscribe;
}, []);
useEffect(() => {
requestUserPermission();
setTimeout(() => {
checkApplicationPermission();
}, 3000);
}, []);
view raw .js hosted with ❤ by GitHub

4. Add ios steps follow below document

Step 2: Install Firebase Admin SDK

pip install firebase-admin
view raw Shell Script hosted with ❤ by GitHub

Step 3: Initialize the Firebase Admin SDK

Push Notification SDK
import firebase_admin
from firebase_admin import credentials, messaging
# Path to your service account key file
cred = credentials.Certificate('path/to/serviceAccountKey.json')
firebase_admin.initialize_app(cred)
view raw .py hosted with ❤ by GitHub

Step 4: Compose and Send the Notification

def send_push_notification(token, title, body):
# Create a message to send to the device
message = messaging.Message(
notification=messaging.Notification(
title=title,
body=body,
),
token=token,
)
# Send the message
response = messaging.send(message)
print('Successfully sent message:', response)
# Example usage
device_token = 'your_device_token'
notification_title = 'Hello'
notification_body = 'This is a push notification'
send_push_notification(device_token, notification_title, notification_body)
view raw .py hosted with ❤ by GitHub

Step 5: Enable Necessary APIs in Google Cloud Console

  1. Firebase Cloud Messaging API
    • Guide the reader to the Google Cloud Console.
    • Show how to navigate to API & Services > Library.
    • Instruct on enabling the Firebase Cloud Messaging API.
  2. Cloud Functions API (if needed)
    • Explain the optional usage and how to enable it.

Conclusion

Summarize the steps covered in the blog. Highlight the simplicity and effectiveness of using Python and Firebase for sending push notifications. Encourage readers to experiment further and explore more advanced features of Firebase Cloud Messaging.

Additional Resources

Provide links to additional resources and documentation: