Home > Web Front-end > JS Tutorial > body text

How to implement push notifications in React Native (Android)

Mary-Kate Olsen
Release: 2024-09-19 18:15:13
Original
1049 people have browsed it

Ever thought about the notifications we receive from the apps we installed? or How is Swiggy or Zomato provoking us to order food at 3 AM with their creative notifications? ?

Let's dive deep into the concept of notifications!

What are notifications?

A notification is a message or alert sent by an app to inform users about updates, events, or actions, typically delivered outside the app's interface.

Now there can be two types of notifications as shown below -

How to implement push notifications in React Native (Android)

Push Notification

Push notifications are messages or alerts sent from a server to an app when the app is not actively running in the foreground. They are primarily used to keep users engaged by sending updates, reminders, or personalized content. Push notifications are delivered through operating system services like Apple Push Notification Service (APNs) for iOS or Firebase Cloud Messaging (FCM) for Android.

How push notification works:

  1. Registration: When the app is installed or first opened, the app requests a unique device token from the OS's push notification service (APNs or FCM).
  2. Server Communication: The app sends this token to the app's backend server, which stores it for future use.
  3. Sending Notifications: The server sends a notification payload (containing title, message, action buttons, etc.) to the push notification service (APNs/FCM) with the device token.
  4. Delivery: The push notification service delivers the message to the respective device, even if the app is not running.

In-App Notification

In-app notifications are messages or alerts displayed to users while they are actively using the app. Unlike push notifications, these do not require server intervention and are triggered within the app itself, usually as a result of user actions or app events.

How in-app notification works:

  1. Event Trigger: When a specific event occurs inside the app (like a user reaching a milestone or a feature needing attention), the app can trigger an in-app notification.
  2. Display: The notification is shown as a banner, modal, or pop-up within the app's UI, guiding the user or informing them about the event.
  3. Custom Logic: In-app notifications are handled directly by the app’s code and can be shown dynamically based on the app’s internal state or logic.

Implementation in React Native android app:

Now that we know about notifications and their types, it's time to implement the feature in your very own react native app. This guide is for implementing only push notification in React native android app only, if you want for iOS or in-app notification, write down a comment and I will post that for sure!

To get started we will be using a third-party service called OneSignal. I recently came across this platform and was shocked by the services they offer.

About OneSignal:

How to implement push notifications in React Native (Android)

OneSignal is a push notification service that enables app developers to send targeted notifications to users across various platforms, including mobile apps, websites, and email. It supports push, in-app, and web notifications, providing features like segmentation, automation, A/B testing, and real-time analytics. OneSignal is widely used for improving user engagement and retention by offering an easy-to-integrate solution for sending personalized messages. Their free tier consists of 10,000/month Free Email Sends, Unlimited Mobile Push Sends, Journeys Workflows, GDPR Compliant, A/B Testing


Going back to the guide, since we already know that push notifications require server-side handling via FCM (Firebase Cloud Messaging) hence there are a few steps to follow:

  1. Set up firebase project (ignore first two steps if you already have firebase project):

    • Pergi ke firebase console dan log masuk ke akaun anda.
    • Buat projek dari sini dan ikuti langkah-langkahnya How to implement push notifications in React Native (Android)
    • Setelah projek anda dibuat pergi ke tetapan projek dari bar sisi How to implement push notifications in React Native (Android)
    • Navigasi ke akaun perkhidmatan dari bar dan ia sepatutnya kelihatan seperti ini How to implement push notifications in React Native (Android)
    • Klik pada Jana kunci peribadi baharu dan ini akan memuat turun fail json, simpan dengan teliti di tempat yang selamat, kami akan memerlukannya semasa menyediakan OneSignal.
  2. Sediakan OneSignal

    • Pergi ke OneSignal dan buat akaun.
    • Selepas membuat akaun, ikuti langkah persediaan dan buat organisasi dan sekarang, anda akan melihat halaman untuk menambah apl.
    • Dalam halaman ini berikan nama apl anda dan pilih Google Android (FCM) untuk kes kami. How to implement push notifications in React Native (Android) dan klik pada Konfigurasikan Platform Anda
    • Kini anda akan dialihkan ke halaman ini di mana kami akan menggunakan fail json akaun perkhidmatan yang dimuat turun semasa konfigurasi firebase How to implement push notifications in React Native (Android) Muat naik json dan kemudian Simpan & Teruskan
    • Pada halaman seterusnya pilih React Native/Expo sebagai SDK sasaran dan kemudian Simpan & Teruskan sekali lagi
    • Dalam skrin seterusnya anda akan mendapat ID Apl anda, ini adalah id sulit dan menggunakan id ini sesiapa sahaja boleh mencetuskan pemberitahuan dalam apl anda, jadi berhati-hati dengan rahsia ini.

Kami telah selesai dengan persediaan dalam firebase dan OneSignal, kini satu-satunya tugas yang tinggal ialah beberapa Kopi dengan Kod

Tambahkan OneSignal pada apl anda dan konfigurasikannya

  • Langkah 1: Tambahkan OneSignal pada apl anda dengan menjalankan arahan ini dahulu
                       npm i react-native-onesignal
Copy after login
  • Langkah 2: Dalam index.js atau App.tsx atau App.js anda, mana-mana punca projek anda, import OneSignal
             import { OneSignal } from 'react-native-onesignal';
Copy after login

dan anda telah menambah coretan kod ini untuk memulakan OneSignal

                    OneSignal.initialize('YOUR_APP_ID');
Copy after login

Anda boleh membungkusnya di dalam cangkuk useEffect untuk penyepaduan dan ketersambungan yang lancar dengan OneSignal.

Ini akan memulakan peranti dengan ID unik dihidupkan untuk OneSignal dan anda boleh menyemaknya dalam langganan di bar sisi. Setiap peranti yang dimulakan akan dikenal pasti dengan OneSignal ID unik ini dan anda boleh menetapkannya secara manual juga jika anda mempunyai pengguna dengan id unik mereka sendiri dengan menggunakan coretan kod ini:

                         OneSignal.login(userId)
Copy after login

Setelah pengguna berjaya melanggan, ia akan dipaparkan dalam papan pemuka seperti ini
How to implement push notifications in React Native (Android)

Sekarang anda mungkin menghadapi beberapa isu dengan OneSignal tidak digunakan dengan betul atau beberapa ralat kritikal jadi berikut ialah bahagian yang boleh anda ikuti yang membantu saya menyelesaikan isu tersebut.

  • Langkah 3: Di dalam androidappbuild.gradle anda tambahkan coretan kod ini
dependencies{
...
implementation('com.onesignal:OneSignal:[3.15.4, 3.99.99]')
...
}
Copy after login
  • Langkah 4: Dalam android untuk menyediakan kebenaran yang diperlukan untuk pemberitahuan tolak, dalam androidappsrcmainAndroidManifest.xml tambah
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
Copy after login

sebelum teg aplikasi. Kebenaran INTERNET adalah pilihan walau bagaimanapun kerana ia mungkin didayakan secara lalai.

Boom? Semua langkah dilindungi untuk melaksanakan pemberitahuan tolak dan anda boleh menghantar pemberitahuan ujian daripada papan pemuka OneSignal itu sendiri.

Cuba sendiri dan jika ada keraguan anda boleh komen di bawah. Ikuti untuk panduan yang lebih terperinci!

Rujukan:
https://documentation.onesignal.com/docs/react-native-sdk-setup
https://documentation.onesignal.com/reference/push-notification
https://medium.com/tribalscale/mobile-push-notifications-implementation-in-react-native-with-one-signal-4e810dddd350

Selamat pengekodan!??‍?

The above is the detailed content of How to implement push notifications in React Native (Android). For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!