OneSignal Help & Documentation

Welcome to the OneSignal New IA developer hub. You'll find comprehensive guides and documentation to help you start working with OneSignal New IA as quickly as possible, as well as support if you get stuck. Let's jump right in!

Get Started    Discussions

Service Extensions

Using the iOS Notification Service Extension and Android Notification Extender Service in your mobile apps.

Jump to Notification Extender Service Android

Notification Service Extension

iOS

Setup instructions can be found in each individual SDK setup guide.

UNNotificationServiceExtension Apple doc

If you are planning to implement any of these features, the Notification Service Extension must be set up:

Getting a payload from a notification

iOS

In this example, we are setting Additional Data through the OneSignal dashboard to {"custom_message":"Hullabaloo, Caneck, Caneck"}

NSDictionary* dict = request.content.userInfo;
NSString* custom = [dict objectForKey:@"custom"];
NSString* aps = [dict objectForKey:@"aps"];

NSLog(@"Running NotificationServiceExtension: custom = %@", custom);
NSLog(@"Running NotificationServiceExtension: aps = %@", aps);
let userInfo = request.content.userInfo

print("Running NotificationServiceExtension: userInfo = \(userInfo.description)")

Example console output:
The additional data can then be extracted from the custom object using the a parameter...


Notification Extender Service

Android
Note! This requires writing native Android code

Set up the NotificationExtenderService if you want to do one of the following:

  • Receive data in the background with or without displaying a notification.
  • Override specific notification settings depending on client side app logic such as custom accent color, vibration pattern, or other any other NotificationCompat options available. See Android's documentation on the NotificationCompat options.

🚧

OneSignal also supports sending additional data along with a notification as key value pairs. You can read this additional data when a notification is opened by adding a setNotificationOpenedHandler instead.

Setup

1. Create a class that extends NotificationExtenderService and implement the onNotificationProcessing method.

For Silent Notifications (notifications that do not show content to the user) make sure to return true

import com.onesignal.OSNotificationPayload;
import com.onesignal.NotificationExtenderService;

public class NotificationExtenderBareBonesExample extends NotificationExtenderService {
   @Override
   protected boolean onNotificationProcessing(OSNotificationReceivedResult receivedResult) {
      // Read properties from result.
     
      // Return true to stop the notification from displaying.
      return false;
   }
}

2. Add the following to your AndroidManifest.xml.

Replace 'YOUR_CLASS_NAME' with the class name you used above.

<service
   android:name=".YOUR_CLASS_NAME"//.NotificationExtenderExample in example below
   android:permission="android.permission.BIND_JOB_SERVICE"
   android:exported="false">
   <intent-filter>
      <action android:name="com.onesignal.NotificationExtender" />
   </intent-filter>
</service>

3. To override or extend specific notification properties call displayNotification with OverrideSettings.

import android.support.v4.app.NotificationCompat;
import com.onesignal.OSNotificationPayload;
import com.onesignal.NotificationExtenderService;
import java.math.BigInteger;

public class NotificationExtenderExample extends NotificationExtenderService {
   @Override
   protected boolean onNotificationProcessing(OSNotificationReceivedResult receivedResult) {
      OverrideSettings overrideSettings = new OverrideSettings();
      overrideSettings.extender = new NotificationCompat.Extender() {
         @Override
         public NotificationCompat.Builder extend(NotificationCompat.Builder builder) {
            //Force remove push from Notification Center after 30 minutes
            builder.setTimeoutAfter(1800000)
            // Sets the background notification color to Green on Android 5.0+ devices.
                   .setColor(new BigInteger("FF00FF00", 16).intValue());
            return builder;
         }
      };

      OSNotificationDisplayedResult displayedResult = displayNotification(overrideSettings);
      Log.d("OneSignalExample", "Notification displayed with id: " + displayedResult.androidNotificationId);

      return true;
   }
}

Getting a payload from a notification

Android

The OSNotificationReceivedResult class has a parameter payload of type OSNotificationPayload which can be used to get the notification message, additional data, and more.

Additionally, the payload object has the following two parameters:

NameTypeDetails
restoringbooleanTrue if the notification was restored after an app update, device reboot, and app opened after being force killed. If you have customized any alerting / priority settings check the restoring flag before applying them. You may want to omit displaying if your notification is no longer relevant to the user.
isAppInFocusbooleanTrue if the app is open and in focus when the notification arrives.

EXAMPLE:

public class NotificationExtenderExample extends NotificationExtenderService {
   @Override
   protected boolean onNotificationProcessing(OSNotificationReceivedResult receivedResult) {
      OverrideSettings overrideSettings = new OverrideSettings();
      overrideSettings.extender = new NotificationCompat.Extender() {
         @Override
         public NotificationCompat.Builder extend(NotificationCompat.Builder builder) {
            if (!receivedResult.restoring) {
               // Only set custom channel if notification is not being restored
               // Note: this would override any channels set through the OneSignal dashboard
               return builder.setChannelId("News");
            }
         }
      };
     
      /* Do something with notification payload */
      String title = receivedResult.payload.title;
      String body  = receivedResult.payload.body;
      String additionalData = receivedResult.payload.additionalData;
     
      // Writes additionalData values to local database
      SQLiteDatabase db = dbHelper.getWritableDatabase();
      ContentValues values = new ContentValues();
      values.put(FeedEntry.COLUMN_NAME_ARTICLE_TITLE, additionalData.articleTitle);
      values.put(FeedEntry.COLUMN_NAME_ARTICLE_ID, additionalData.articleId);
      long newRowId = db.insert(FeedEntry.TABLE_NAME, null, values);
      // ...
     
      return true;
   }
}

Additional Notes

  • NotificationExtenderService is an Android IntentService so please do all your work synchronously. A wake lock is obtained so the device will not sleep while you're processing the payload.
  • By default BigTextStyle is set so to change the body text you must override the style with the following:
.setStyle(new NotificationCompat.BigTextStyle().bigText(message))

Troubleshooting the iOS Notification Service Extension

If you are having issues with Confirmed Deliveries or Images not showing on iOS mobile apps follow this guide.

1 Open the NotificationService.m or NotificationService.swift and replace the whole file contents with the below code. (The code is the same as our original setup code, just adding some additional logging.

#import <OneSignal/OneSignal.h>

#import "NotificationService.h"

@interface NotificationService ()

@property (nonatomic, strong) void (^contentHandler)(UNNotificationContent *contentToDeliver);
@property (nonatomic, strong) UNNotificationRequest *receivedRequest;
@property (nonatomic, strong) UNMutableNotificationContent *bestAttemptContent;

@end

@implementation NotificationService

- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler {
    self.receivedRequest = request;
    self.contentHandler = contentHandler;
    self.bestAttemptContent = [request.content mutableCopy];
    
    [OneSignal didReceiveNotificationExtensionRequest:self.receivedRequest withMutableNotificationContent:self.bestAttemptContent];
    
    // DEBUGGING: Uncomment the 2 lines below and comment out the one above to ensure this extension is excuting
    //            Note, this extension only runs when mutable-content is set
    //            Setting an attachment or action buttons automatically adds this
    NSLog(@"Running NotificationServiceExtension");
    self.bestAttemptContent.body = [@"[Modified] " stringByAppendingString:self.bestAttemptContent.body];
    
  NSUserDefaults *userDefault = [[NSUserDefaults alloc] initWithSuiteName:@"group.com.onesignal.jonexample.onesignal"];
    NSLog(@"NSE player_id: %@", [userDefault  stringForKey:@"GT_PLAYER_ID"]);
    NSLog(@"NSE app_id: %@", [userDefault  stringForKey:@"GT_APP_ID"]);
    
    self.contentHandler(self.bestAttemptContent);
}

- (void)serviceExtensionTimeWillExpire {
    // Called just before the extension will be terminated by the system.
    // Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
    
    [OneSignal serviceExtensionTimeWillExpireRequest:self.receivedRequest withMutableNotificationContent:self.bestAttemptContent];
    
    self.contentHandler(self.bestAttemptContent);
}

@end
import UserNotifications

import OneSignal

class NotificationService: UNNotificationServiceExtension {
    
    var contentHandler: ((UNNotificationContent) -> Void)?
    var receivedRequest: UNNotificationRequest!
    var bestAttemptContent: UNMutableNotificationContent?
    
    override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
        self.receivedRequest = request;
        self.contentHandler = contentHandler
        bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
        
        let userInfo = request.content.userInfo
        
        print("Running NotificationServiceExtension: userInfo = \(userInfo.description)")
        
        
        if let bestAttemptContent = bestAttemptContent {
            OneSignal.didReceiveNotificationExtensionRequest(self.receivedRequest, with: self.bestAttemptContent)
            contentHandler(bestAttemptContent)
        }
    }
    
    override func serviceExtensionTimeWillExpire() {
        // Called just before the extension will be terminated by the system.
        // Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
        if let contentHandler = contentHandler, let bestAttemptContent =  bestAttemptContent {
            OneSignal.serviceExtensionTimeWillExpireRequest(self.receivedRequest, with: self.bestAttemptContent)
            contentHandler(bestAttemptContent)
        }
    }
    
}

2 Replace group.com.onesignal.jonexample.onesignal with your App Groups Name

3 Build and run the project in Xcode on your device. Then select Window > Devices and Simulators

4 Select Open Console

5 Send this device a notification and then search in the console for NSE player_id and NSE app_id

You should see a message with the device's OneSignal Player Id and OneSignal App Id based on the search.

Updated 22 days ago


Service Extensions


Using the iOS Notification Service Extension and Android Notification Extender Service in your mobile apps.

Suggested Edits are limited on API Reference Pages

You can only suggest edits to Markdown body content, but not to the API spec.