react-native-push-notification

repository·master·Indexed 27 days ago

https://github.com/zo0r/react-native-push-notification

A library for handling both local and remote push notifications in React Native applications for iOS and Android. Version 8.1.1 supports triggering immediate local notifications, scheduling notifications for specific times or repeating intervals, and managing Android notification channels. It includes features for custom notification sounds, inline replies on Android, and integration with Firebase and Play Services for remote notifications.

Tokens
6.2K
Snippets
15
Records
30
Agent score
92%

What's inside react-native-push-notification

  1. Configure custom notification sounds

    master

    To use custom sounds, place the audio files in the following locations:

    • Android: [project_root]/android/app/src/main/res/raw
    • iOS: Add the file to the project Resources in Xcode.

    In the notification options object, specify the filename using soundName: soundName: 'my_sound.mp3'

  2. Implement Android notification actions and inline replies

    master

    Android allows adding interactive buttons to notifications via the actions parameter (an array of strings).

    Inline Reply

    To enable inline text input, add "ReplyInput" to the actions array. You must also provide reply_placeholder_text and reply_button_text.

    To retrieve the user's response in your onNotification handler, check the action property and access notification.reply_text.

    Requirement: You must add the following receiver to your AndroidManifest.xml:

    <receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationActions" />
    // Schedule a notification with inline reply
    PushNotification.localNotificationSchedule({
      message: "My Notification Message",
      date: new Date(Date.now() + (60 * 1000)),
      actions: ["ReplyInput"],
      reply_placeholder_text: "Write your response...",
      reply_button_text: "Reply"
    });
    
    // Handling the reply in onNotification
    // ...
    if(notification.action === "ReplyInput"가){
      console.log("texto", notification.reply_text)
    }
  3. Configure Android build.gradle for Firebase and Play Services

    master

    When using remote notifications, ensure firebase-messaging and google-services are correctly configured in your Gradle files. Note that firebase-core is no longer needed; use firebase-analytics instead.

    // In android/build.gradle
    ext {
        googlePlayServicesVersion = "<Your play services version>"
        firebaseMessagingVersion = "<Your Firebase version>"
        // ... other settings
    }
    
    buildscript {
        dependencies {
            classpath('com.google.gms:google-services:4.3.3')
        }
    }
    
    // In android/app/build.gradle
    dependencies {
      implementation 'com.google.firebase:firebase-analytics:17.3.0'
    }
    
    apply plugin: 'com.google.gms.google-services'
  4. Handle Android custom notification payloads

    master

    If your 3rd party notification provider uses a custom data format that react-native-push-notification cannot parse, you must implement a custom IntentHandler in your Android native code (Application init or MainActivity.onCreate()).

    1. Remove the default intent handler from AndroidManifest.xml.
    2. Implement onNewIntent to parse the intent.
    3. Implement getBundleFromIntent to return the bundle that will be serialized into notification.data for the onNotification() handler.
    // Android Native Implementation
    RNPushNotification.IntentHandlers.add(new RNPushNotification.RNIntentHandler() {
      @Override
      public void onNewIntent(Intent intent) {
        // Custom parsing logic here
      }
    
      @Nullable
      @Override
      public Bundle getBundleFromIntent(Intent intent) {
        if (intent.hasExtra("MY_NOTIFICATION_PROVIDER_DATA_KEY")) {
          return intent.getBundleExtra("MY_NOTIFICATION_PROVIDER_DATA_KEY");
        }
        return null;
      }
    });
  5. Set default notification channel in AndroidManifest

    master

    You can define a default notification channel in your AndroidManifest.xml to avoid manual channel management for local notifications.

    For react-native-push-notification, use the following metadata:

    <meta-data
        android:name="com.dieam.reactnativepushnotification.default_notification_channel_id"
        android:value="@string/default_notification_channel_id" />

    If this is not defined, the library falls back to the Firebase default channel ID: fcm_fallback_notification_channel.

  6. Schedule repeating notifications

    master

    You can schedule notifications to repeat at specific intervals.

    iOS

    Use repeatType. Supported values: month, week, day, hour, minute. Note: repeatTime is not supported on iOS.

    Android

    Use repeatType. Supported values: month, week, day, hour, minute, time. If repeatType is set to time, you must provide repeatTime as the number of milliseconds between intervals.

    // Android example: Every other day
    PushNotification.localNotificationSchedule({
        ... 
        repeatType: 'day',
        repeatTime: 2,
        ...
    });
  7. Configure Android manual installation for Scheduled Notifications

    master

    To use localNotificationSchedule(), you must manually update your AndroidManifest.xml with specific permissions, metadata, and receivers. Note that localNotification() works without these changes.

    <!-- In android/app/src/main/AndroidManifest.xml -->
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
    
    <application ....>
        <!-- Set to true to enable pop-up for in foreground on receiving remote notifications -->
        <meta-data  android:name="com.dieam.reactnativepushnotification.notification_foreground"
                    android:value="false"/>
        <!-- Set your App's accent color -->
        <meta-data  android:name="com.dieam.reactnativepushnotification.notification_color"
                    android:resource="@color/white"/>
    
        <receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationActions" />
        <receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationPublisher" />
        <receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationBootEventReceiver">
            <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>
    </application>
  8. Manage Android Notification Channels

    master

    Android requires notification channels to be created before they can be used. When triggering a notification, you must provide a channelId that matches a created channel.

    Note: Once a channel is created, its options cannot be updated. To change channel settings, you must create a new channel with a different channelId.

    Create a Channel

    Use PushNotification.createChannel(options, callback) to register a channel. The callback returns true if the channel was newly created, or false if it already existed.

    List Channels

    Use PushNotification.getChannels(callback) to retrieve an array of available channel IDs.

    Check Channel Status

    • PushNotification.channelExists(channel_id, callback): Returns true/false if the channel exists.
    • PushNotification.channelBlocked(channel_id, callback): Returns true/false if the channel is blocked by the user.

    Delete a Channel

    Use PushNotification.deleteChannel(channel_id) to remove a channel.

    import PushNotification, {Importance} from 'react-native-push-notification';
    
    PushNotification.createChannel(
      {
        channelId: "channel-id", // (required)
        channelName: "My channel", // (required)
        channelDescription: "A channel to categorise your notifications", // (optional)
        playSound: false,
        soundName: "default",
        importance: Importance.HIGH,
        vibrate: true,
      },
      (created) => console.log(`createChannel returned '${created}'`)
    );
    
    // List channels
    PushNotification.getChannels(function (channel_ids) {
      console.log(channel_ids); // ['channel_id_1']
    });
    
    // Check if exists
    PushNotification.channelExists('channel-id', (exists) => {
      console.log(exists); // true/false
    });
    
    // Check if blocked
    PushNotification.channelBlocked('channel-id', (blocked) => {
      console.log(blocked); // true/false
    });
    
    // Delete channel
    PushNotification.deleteChannel('channel-id');
  9. Configure notification priority, visibility, and importance

    master

    When scheduling or creating notifications, you can customize their behavior using the following options:

    Priority

    Sets the priority level. Default is "high". Options: "max", "high", "low", "min", "default".

    Visibility

    Sets how the notification is visible. Default is "private". Options: "private", "public", "secret".

    Importance

    Sets the importance level using the Importance object. Options: Importance.DEFAULT, Importance.HIGH, Importance.LOW, Importance.MIN, Importance.NONE, Importance.UNSPECIFIED.

  10. Initialize PushNotification.configure()

    master

    Initialize the notification service using PushNotification.configure().

    CRITICAL: Do NOT call .configure() inside a component (even App). It must be called in the app's entry point (e.g., index.js) to ensure notification handlers are loaded correctly.

    import PushNotificationIOS from "@react-native-community/push-notification-ios";
    import PushNotification from "react-native-push-notification";
    
    PushNotification.configure({
      onRegister: function (token) {
        console.log("TOKEN:", token);
      },
    
      onNotification: function (notification) {
        console.log("NOTIFICATION:", notification);
        // Required for iOS
        notification.finish(PushNotificationIOS.FetchResult.NoData);
      },
    
      onAction: function (notification) {
        console.log("ACTION:", notification.action);
        console.log("NOTIFICATION:", notification);
      },
    
      onRegistrationError: function(err) {
        console.error(err.message, err);
      },
    
      permissions: {
        alert: true,
        badge: true,
        sound: true,
      },
    
      popInitialNotification: true,
      requestPermissions: true,
    });