Documentation

React Native Android Setup


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

Note: Part of this guide requires that you open the underlying android/ project with Android Studio.

Get the SDK

Import version 1.0.28 of our SDK and version 1.0.2 of our React Native SDK by adding the following dependencies to your app's build.gradle:

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

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

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


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

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

Make sure to import me.pushy.sdk.react.PushyPackage for this code to work.

Modify AndroidManifest

Add the following lines to your 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.


Add the following lines to your AndroidManifest.xml, 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.PACKAGE_REPLACED" />
        <data android:scheme="package" />
    </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 socket service -->
<service android:name="me.pushy.sdk.services.PushySocketService"/>

<!-- Pushy Notification Service -->
<!-- Do not modify - internal notification service that forwards notifications to your React Native app -->
<service android:name="me.pushy.sdk.react.services.PushyNotificationService"/>

<!-- End Pushy Declarations -->
Install the JavaScript 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

Then, require the package in your index.android.js file like so:

import Pushy from 'pushy-react-native';
Modify Index Component

Invoke Pushy.listen() in your index component'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

Skip this if your targetSdkLevel is less than 23.

Android 6.0 and newer versions require apps with a targetSdkLevel >= 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:
// 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
      }
    });
  }
});

Make sure to import PermissionsAndroid from react-native for this code to work.

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) => {
    // Print device token to console
    console.log('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, do something to alert the user
}).catch((err) => {
    // Handle registration errors
    console.error(err);
});
Handle Notifications

Call the Pushy.setNotificationListener((data) => {}) method in your index.android.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 = 'Pushy';

  // 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 request the android.permission.VIBRATE permission within your 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.

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
      console.log('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 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 help you out.

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.