Documentation

React Native Setup


To start sending push notifications to your React Native app with Pushy, you'll need to make a few changes to your application.

Create an App

The first step involves signing up and creating your first app on Pushy.

If you have already created your app on Pushy for another platform, simply configure your existing app with your Android Package Name & iOS Bundle ID in the App Settings tab and proceed to the next step.

Note: You can upgrade to our Pro plan at any time by setting up a payment method in the Billing page.


Click Create and proceed to the next step.

Install the SDK

Run the following command in the root directory of your project to install the pushy-react-native package from npm:

npm install pushy-react-native --save

Run the following command to link the ios native module to your project:

react-native link pushy-react-native
Enable Push Capability (iOS)

You must enable the Push Notifications capability manually for your iOS app to register for and receive push notifications. Open your React Native iOS app in Xcode by running the following command in your project root:

open ios/*.xc*

Then, visit the project editor, select the Capabilities tab, and turn on the Push Notifications capability:

Note: Xcode should display two checkmarks indicating that the capability was successfully enabled.

Add Blank Swift File

To avoid a compilation error, please add a blank .swift file to your Xcode project. This file can be empty. When prompted, you may decline the creation of a bridging header for your project.

You may close the Xcode project now.

Import Android SDK

Import version 1.0.42 of the Pushy Android SDK and version 1.0.6 of our React Native SDK by adding the following dependencies to your android/app/build.gradle, within the dependencies {} declaration:

// Pushy SDK for Android
compile 'me.pushy:sdk:1.0.42'

// Pushy SDK for React Native Android
compile 'me.pushy:sdk-react-native:1.0.6'

Alternatively, download sdk-1.0.42.jar and sdk-react-native-1.0.6.jar and include them manually. If you're interested, check out the SDK changelog to see what's new in the latest version of the Pushy Android SDK.


Load the native PushyPackage within your MainApplication.java class by initializing and returning it within the getPackages() method implementation:

import me.pushy.sdk.react.PushyPackage;

@Override
protected List getPackages() {
    return Arrays.asList(
        new MainReactPackage(),
        new PushyPackage()
    );
}
Modify AndroidManifest

Add the following lines to your android/app/src/main/AndroidManifest.xml, inside the <manifest> tag:

<!-- Pushy Permissions -->
                                    
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

<!-- End Pushy Permissions -->

You should manually omit any permission declarations that your app already asks for.

Note: android.permission.WRITE_EXTERNAL_STORAGE is optional - it is necessary only for persisting device tokens in the external storage for when your app is reinstalled, so we don't charge you twice for the same device. If this permission is not declared, the SDK will persist device tokens only within your app's SharedPreferences, which are cleared when your app is uninstalled.


Additionally, add the following declarations inside the <application> tag:

<!-- Pushy Declarations -->

<!-- Pushy Notification Receiver -->
<!-- Do not modify - internal BroadcastReceiver that forwards notifications to the internal notification service-->
<receiver android:name="me.pushy.sdk.react.receivers.PushReceiver" android:exported="false">
    <intent-filter>
        <!-- Do not modify this -->
        <action android:name="pushy.me" />
    </intent-filter>
</receiver>

<!-- Pushy Update Receiver -->
<!-- Do not modify - internal BroadcastReceiver that restarts the listener service -->
<receiver android:name="me.pushy.sdk.receivers.PushyUpdateReceiver" android:exported="false">
    <intent-filter>
        <action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
    </intent-filter>
</receiver>

<!-- Pushy Boot Receiver -->
<!-- Do not modify - internal BroadcastReceiver that restarts the listener service -->
<receiver android:name="me.pushy.sdk.receivers.PushyBootReceiver" android:exported="false">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED"/>
    </intent-filter>
</receiver>

<!-- Pushy Socket Service -->
<!-- Do not modify - internal service -->
<service android:name="me.pushy.sdk.services.PushySocketService"/>

<!-- Pushy Job Service (added in Pushy SDK 1.0.35) -->
<!-- Do not modify - internal service -->
<service android:name="me.pushy.sdk.services.PushyJobService"
    android:permission="android.permission.BIND_JOB_SERVICE"
    android:exported="true" />

<!-- End Pushy Declarations -->
Modify App Component

Require the package in your App.js file like so:

import Pushy from 'pushy-react-native';

Invoke Pushy.listen() in your App.js's componentDidMount() method so that Pushy's internal notification listening service will start itself, if necessary:

componentDidMount() {
   // Start the Pushy service
   Pushy.listen();
}
Android 6.0+ Compatibility

Android 6.0 and newer versions require apps with a targetSdkVersion >= 23 to explicitly request permissions from users via permission dialogs.

Since Pushy persists device tokens in the external storage (to survive app reinstallation), you should add the following code to ask the user to grant your app permission to access the external storage.

Find:
Pushy.listen();
Add Below:
// Only necessary for Android
if (Platform.OS === 'android') {
    // Check whether the user has granted the app the WRITE_EXTERNAL_STORAGE permission
    PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE).then((granted) => {
        if (!granted) {
            // Request the WRITE_EXTERNAL_STORAGE permission so that the Pushy SDK will be able to persist the device token in the external storage
            PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE).then((result) => {
                // User denied permission?
                if (result !== PermissionsAndroid.RESULTS.GRANTED) {
                    // Possibly ask the user to grant the permission
                }
            });
        }
    });
}

Note: Please add import {PermissionsAndroid} from 'react-native'; to the top of the file.

Register Devices

Devices need to be uniquely identified to receive push notifications.

Every device is assigned a unique token that you can use to push it at any given time. Once the device has been assigned a token, it should be stored in your application's backend database. When you're ready to push the device, your backend server will send its token to our REST API, and we'll deliver the push notification to the corresponding device.


Add the following code within a Component method (i.e. componentDidMount) to register the device for push notifications:

// Register the device for push notifications
Pushy.register().then(async (deviceToken) => {
    // Display an alert with device token
    alert('Pushy device token: ' + deviceToken);

    // Send the token to your backend server via an HTTP GET request
    //await fetch('https://your.api.hostname/register/device?token=' + deviceToken);

    // Succeeded, optionally do something to alert the user
}).catch((err) => {
    // Handle registration errors
    console.error(err);
});
Handle Notifications

Call the Pushy.setNotificationListener((data) => {}) method in your App.js file, outside the Component class declaration:

// Handle push notifications
Pushy.setNotificationListener(async (data) => {
    // Print notification payload data
    console.log('Received notification: ' + JSON.stringify(data));

    // Notification title
    let notificationTitle = 'MyApp';

    // Attempt to extract the "message" property from the payload: {"message":"Hello World!"}
    let notificationText = data.message || 'Test notification';

    // Display basic system notification
    Pushy.notify(notificationTitle, notificationText);
});

This method can only be called once for your entire app lifecycle, therefore, it should not be invoked within a Component lifecycle event.


Note: Please make sure to add the android.permission.VIBRATE permission declaration within your android/app/src/main/AndroidManifest.xml if you'd like the notification to vibrate the device.

Feel free to modify this sample code to suit your own needs. In the next step, we'll take a look at how to parse the incoming payload data sent by your backend server.

Custom Notification Icon (Android)

Optionally configure a custom notification icon for incoming Android notifications by placing icon file(s) in android/app/src/main/res/drawable-* and calling:

Pushy.setNotificationIcon('ic_notification');

Replace ic_notification with the resource file name, excluding the extension.

Note: If you don't call this method, or an invalid resource is provided, a generic icon will be used instead.

Parse Notification Data

Any payload data that you send with your push notifications is made available to your app via the data parameter of your notification listener.

If you were to send a push notification with the following data:

{"id": 1, "success": true, "message": "Hello World"}

Then you'd be able to retrieve each value from within your notification listener callback like so:

let id = data.id; // number
let success = data.success; // bool
let message = data.message; // string

Note: Unlike GCM / FCM, we do not stringify your payload data, except if you supply JSON objects or arrays.

Subscribe to Topics (Optional)

Optionally subscribe the device to one or more topics to target multiple users with a shared interest when sending notifications.

Depending on your app's notification criteria, you may be able to leverage topics to simply the process of sending the same notification to multiple users. If your app only sends personalized notifications, skip this step and simply target individual devices by specifying their tokens.


Add the following code within a Component method (i.e. componentDidMount) to subscribe a registered device to a topic:

// Make sure the device is registered
Pushy.isRegistered().then((isRegistered) => {
  if (isRegistered) {
    // Subscribe the device to a topic
    Pushy.subscribe('news').then(() => {
      // Subscribe successful
      alert('Subscribed to topic successfully');
    }).catch((err) => {
      // Handle errors
      console.error(err);
    });
  }
});

Note: Replace news with your own case-sensitive topic name that matches the following regular expression: [a-zA-Z0-9-_.]+.


You can then notify multiple devices subscribed to a certain topic by specifying the topic name (prefixed with /topics/) as the to parameter in the Send Notifications API.

Send Test Notification

Input your device token and select your app to send a test push notification:

Note: You can specify a topic instead of a device token (i.e. /topics/news). Also, if your app is not automatically detected, please manually copy the Secret API Key from the Dashboard and paste it into the form.

Check if your device received the notification. Did it work? If not, contact us, we'll be glad to help.

Integration Complete


Congratulations on implementing Pushy in your app!

Now, all that's left is to setup your backend. Head on over to the Backend Setup guide to begin persisting device tokens as well as implementing the logic for sending push notifications to your users.