Handle incoming notifications

Beams makes it possible trigger callback code in your application when a push notification arrives on a user's device. This can be used to respond to the arrival of the notification in your application.

Android

Handle all notifications

You can implement a service to handle incoming notifications. It will get called when your application is:

  • In the foreground
  • In the background, and the notification only contains a data payload.

Android Manifest

1
2
3
4
5
6
7
8
9
10
11
<manifest>
    <application>
        ...
        <!-- Add these lines: -->
        <service android:name=".NotificationsMessagingService">
            <intent-filter android:priority="1">
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>
    </application>
</manifest>
When your application is in the background this service will not be called unless there is only a data payload in the notification. The notification key cannot be used.

NotificationsMessagingService.java

1
2
3
4
5
6
7
8
9
10
11
import android.util.Log;

import com.google.firebase.messaging.RemoteMessage;
import com.pusher.pushnotifications.fcm.MessagingService;

public class NotificationsMessagingService extends MessagingService {
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Log.i("NotificationsService", "Got a remote message 🎉");
    }
}

Handle notifications in a particular Activity

When a push notification arrives while your activity is in display, the Beams SDK will call the onMessageReceived listener with a RemoteMessage object containing the notification and data payload.

PHP Server

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var publishResponse = beamsClient.publish(
  ["hello"],
  {
    "fcm": {
      "notification": {
        "title": "Hello",
        "body": "Hello, World!",
      },
      // This data can be used in your activity when a notification arrives
      // with your app in the foreground.
      "data": {
        "inAppNotificationMessage": "Display me somewhere in the app ui!",
      },
  },
);

Android Activity

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Override
protected void onResume() {
    super.onResume();
    PushNotifications.setOnMessageReceivedListenerForVisibleActivity(this, new PushNotificationReceivedListener() {
        @Override
        public void onMessageReceived(RemoteMessage remoteMessage) {
            String messagePayload = remoteMessage.getData().get("inAppNotificationMessage");
            if (messagePayload == null) {
                // Message payload was not set for this notification
                Log.i("MyActivity", "Payload was missing");
            } else {
                Log.i("MyActivity", messagePayload);
                // Now update the UI based on your message payload!
            }
        }
    });
}

iOS

While your app is running or backgrounded

When a notification arrives whilst your app is running (foreground or background) you will receive a callback in your AppDelegate:

AppDelegate

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import UIKit

import PushNotifications


@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    let beamsClient = PushNotifications.shared

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
       let remoteNotificationType = self.beamsClient.handleNotification(userInfo: userInfo)
       if remoteNotificationType == .ShouldIgnore {
           return // This was an internal-only notification from Pusher.
       }

      // Do something fabulous 🦄
    }
}

While your app is closed

Apple does not offer a way to handle a notification that arrives when your app is closed (i.e. when the user has fully quit the application or the OS had decided to kill it while it is in the background). If this happens, the only way to handle the notification is to wait until it is opened by the user.

AppDelegate

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import UIKit

import PushNotifications


@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    let beamsClient = PushNotifications.shared

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        if launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] != nil {
          // The app was launched by the user tapping a notification
        }
    }
}