Push Notification
The push module of Player Network SDK provides a push notification service for the game. There are two types of push functions, local notifications and remote push notifications. The push function enables the game to send push notifications such as holiday activities and anniversary events to the user even when the game is not running.
Due to Android API tightening restrictions for SCHEDULE_EXACT_ALARM
permission requests on Android 12 or later, Player Network SDK is using internal delay triggering to implement push. As such, delay codes cannot be triggered after the app is closed, and the time of triggering may also be affected by system sleep on the device.
Prerequisites
For Local notifications, Integrate the Player Network SDK first.
Remote push notifications are implemented using the push capabilities of Firebase, complete the following procedures in order to use remote push:
1. Register a Firebase project
Go to the Firebase Console and follow the instructions to register a Firebase project.
2. Add an app
Firebase supports multi-store packages through adding multiple apps to the same project. Create additional Firebase apps on the Firebase Console and complete the configurations by repeating the following steps.
In the Project Overview page of the Firebase Console, add the Firebase App for the corresponding platform.
Follow the instructions to enter the relevant information.
Add Firebase to your Android App.
- Enter relevant information, and then click REGISTER APP.
If you are unsure about the values for certain fields, you can add them later. - Download the
google-services.json
file for reference. You can download it again from the Firebase Console. - Skip other steps.
- Enter relevant information, and then click REGISTER APP.
Add Firebase to your iOS App.
- Enter relevant information, and then click REGISTER APP.
If you are unsure about the values for certain fields, you can add them later. - Download the
google-services.json
file for reference. You can download it again from the Firebase Console. - Configure the APNs certificate for the push function.
- Enter relevant information, and then click REGISTER APP.
3. Upload iOS APNs certificate
In the Settings page, click CLOUD MESSAGING to find the iOS project.
Add the development APNs certificate and production APNs certificate respectively.
For more information, see Configuring APNs with FCM.
4. Project configurations
In the Project settings page, you can continue to set up your project, download the google-services.json
file and the GoogleService-Info.plist
file, or configure the Android certificate fingerprint.
Step 1: Set up permissions and configurations
Local notifications
Add the following configuration to INTLConfig.ini for Android.
[Android Local Notification]
ANDROID_LOCAL_NOTIFICATION_ENABLE = 1
Remote push notifications
Configure the push module for remote Firebase push.
Android
User permissions
Because the Firebase SDK is only compatible with minSdkVersion >= 19 or later, it may have problems when running on Android 4.2 or earlier. Set minSdkVersion >= 19 for the game.
Firebase requires permission to access the internet.
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Configurations
Configure the Android client key in the INTLConfig.ini file.
[Google]
GOOGLE_CLIENT_KEY_ANDROID = {YOUR_CLIENT_KEY_ANDROID}
- Replace
{YOUR_CLIENT_KEY_ANDROID}
with Web client Key required by Player Network SDK. It is the client ID for web applications in the Credentials section during API OAuth configuration, also known as Server Client ID during OAuth 2.5 API configuration.
google-services.json
The build will fail without the google-services.json
file.
The gradle build method can directly process the google-services.json
file, and convert the content to a corresponding app/build/generated/res/google-services/{build_type}/values/values.xml
configuration file.
- Unity
- Unreal Engine
For more information on adding and placing the google-services.json
file in the Assets/Plugins/Android/
directory, see The Google Services Gradle Plugin.
For more information on adding and placing the google-services.json
file in the Plugins/INTLSDK/Source/INTLFirebase/Libs/Android
directory, see The Google Services Gradle Plugin.
[Optional] Configure default background color
When configuring push notifications, specify a color to set it as the default background color of the notification banner.
The color
field can be set in the resource file in the Assets/Plugins/Android/
directory of the Android folder of the Unity project.
For example: xxx/res/values/colors.xml.
``` xml
<!-- Set color used with incoming notification messages. This is used when no color is set for the incoming notification message.
See README(https://goo.gl/6BKBk7) for more. -->
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="@color/colorAccent" />
```
[Optional] Configure default icon
When configuring push notifications, specify an icon to set it as the default icon of the notification.
The drawable
file can be placed in the Assets/Plugins/Android/
directory of the Android folder of the Unity project.
For example: xxx/res/drawable.
```xml
<!-- Set custom default icon. This is used when no icon is set for incoming notification messages.
See README(https://goo.gl/l4GJaQ) for more. -->
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="@drawable/ic_stat_ic_notification" />
```
Small and large notification icons are supported on Android.
Small icons are displayed in the status bar at the top, as well as in the notification banner.
noteAndroid 5.0+ (API level 21+) enforces icons to have white and transparent backgrounds. Tinting of the notification banner with an accent color is still allowed, however the color of the icon is unaffected.
Large icons are recommended to be 256x256 pixels in size, and if not set, the small icon will be used instead. The placement of large icons depends on the Android version of the device:
- To the left of the notification text for devices running Android 4.0.3 - 6.0 (API level 15-23).
- To the right of the notification text for devices running Android 7.0+ (API level 24+).
The Notification icon generator may be used to create a push notification icon of the correct size.
Density | Size | File path |
---|---|---|
MDPI | 24 x 24 (drawable-mdpi) | Assets/Plugins/Android/res/drawable-mdpi/ |
HDPI | 36 x 36 (drawable-hdpi) | Assets/Plugins/Android/res/drawable-hdpi/ |
XHDPI | 48 x 48 (drawable-xhdpi) | Assets/Plugins/Android/res/drawable-xhdpi/ |
XXHDPI | 72 x 72 (drawable-xxhdpi) | Assets/Plugins/Android/res/drawable-xxhdpi/ |
XXXHDPI | 96 x 96 (drawable-xxxhdpi) | Assets/Plugins/Android/res/drawable-xxxhdpi/ |
XXXHDPI (Large) | 256 x 256 (drawable-xxxhdpi) (Large) | Assets/Plugins/Android/res/drawable-xxxhdpi/ |
iOS
Configurations
Firebase Plist
The build will fail without the GoogleService-info.plist
file.
Replace the GoogleService-info.plist
configuration file under the Assets/Plugins/iOS/INTLSDK/INTLFirebase/ThirdSDK/
directory.
- Unity
- Unreal Engine
Enable push in the Xcode project
For Unity, Firebase push has to be enabled from your Xcode project. Before exporting the Xcode project, the .projmods file has to be configured first.
Player Network SDK has included the below configurations in the INTLFirebaseKit.projmods
file, ensure that the information is correct.
{
"group": "INTL",
"libs": [],
"frameworks": [],
"files": [
"Plugins/iOS/INTLSDK/INTLFirebase/GoogleService-Info.plist"
],
"folders": [],
"excludes": [],
"headerpaths":[],
"build_settings": {},
"system_capabilities": {"com.apple.Push":"TRUE"},
"Info.plist":{},
}
For more information regarding Xcode project exporting, see Player Network SDK XUPorter solution.
After exporting your Xcode project, enable Remote notifications from under Capability > Background Modes > Push Notifications in the project.
Adapting to iOS push
For Unreal Engine V4.21 or later, modify the below source code:
- IOSAppDelegate.h
class APPLICATIONCORE_API FIOSCoreDelegates
{
public:
// Broadcast when this application is opened from an external source
DECLARE_MULTICAST_DELEGATE_FourParams(FOnOpenURL, UIApplication*, NSURL*, NSString*, id);
DECLARE_MULTICAST_DELEGATE_TwoParams(FApplicationHandleEventsForBackgroundURLSessionDelegate, NSString*, NSDictionary*); // Add this line
static FOnOpenURL OnOpenURL;
static FApplicationHandleEventsForBackgroundURLSessionDelegate OnApplicationHandleEventsForBackgroundURLSessionDelegate; // Add this line
}; - IOSAppDelegate.cpp
extern bool GShowSplashScreen;
FIOSCoreDelegates::FOnOpenURL FIOSCoreDelegates::OnOpenURL;
TArray<FIOSCoreDelegates::FFilterDelegateAndHandle> FIOSCoreDelegates::PushNotificationFilters;
FIOSCoreDelegates::FApplicationHandleEventsForBackgroundURLSessionDelegate FIOSCoreDelegates::OnApplicationHandleEventsForBackgroundURLSessionDelegate; // Add this line- (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)(void))completionHandler
{
FString Id(identifier);
FCoreDelegates::ApplicationBackgroundSessionEventDelegate.Broadcast(Id);
completionHandler();
NSDictionary* dict = [NSDictionary dictionaryWithObjectsAndKeys:completionHandler, @"handler", nil]; // Add this line
FIOSCoreDelegates::OnApplicationHandleEventsForBackgroundURLSessionDelegate.Broadcast(identifier, dict); // Add this line
}
Step 2: Register callbacks
Add the following callbacks for the push module.
- Unity
- Unreal Engine
API | Function |
---|---|
AddPushBaseResultObserver | Register the BaseResult callback of the Player Network SDK push module Used to manage the RegisterPush method callback |
RemovePushBaseResultObserver | Unregister the BaseResult callback |
AddPushResultObserver | Register the PushResult callback of the Player Network SDK push module Used to manage the AddLocalNotification method callback |
RemovePushResultObserver | Unregister the PushResult callback |
API | Function |
---|---|
SetPushBaseResultObserver | Set the BaseResult callback for the Player Network SDK push module |
GetPushBaseResultObserver | Get the BaseResult callback |
OnPushBase_Implementation | Implement the BaseResult callback for the RegisterPush method |
SetPushResultObserver | Set the PushResult callback for the Player Network SDK push module |
GetPushResultObserver | Get the PushResult callback |
OnPushResult_Implementation | Implement the PushResult callback for the AddLocalNotification method |
Step 3: Configure notifications
Local notifications
Call the AddLocalNotification
method.
Remote push notifications
Send push notifications to all devices:
- In the game, call the
RegisterPush
method and then terminate the game. - In the Firebase backend, select Cloud Messaging and then click Create Notification.
- Enter the subject and text for the notification and then click Next.
- Select the bundle to send to the app and then click Next.
- Select the time and then click Review.
- The notification can be pushed once it is approved.
Send push notifications to pushToken registered devices only:
- In the game, call the
RegisterPush
method and then copy the FCM token from the log and terminate the game. - In the Firebase backend, select Cloud Messaging and then click Create Notification.
- Enter the subject and text for the notification and then click Send Text Message.
- Enter the FCM token from the log and then click Test to perform a test push.
Reset iOS app icon badge
- Unity
- Unreal Engine
The below code has to be added to the applicationDidBecomeActive
method of Classes/UnityAppController.mm
in the Xcode project to clear icon badge.
[UIApplication sharedApplication].applicationIconBadgeNumber=0;
Sample code:
- (void)applicationDidBecomeActive:(UIApplication*)application
{
::printf("-> applicationDidBecomeActive()\n");
[self removeSnapshotView]; // The code may be different between Unity versions
[UIApplication sharedApplication].applicationIconBadgeNumber=0; // Add this line
if (_unityAppReady)
{
if (UnityIsPaused() && _wasPausedExternal == false)
{
UnityWillResume();
UnityPause(0);
}
if (_wasPausedExternal)
{
if (UnityIsFullScreenPlaying())
TryResumeFullScreenVideo();
}
UnitySetPlayerFocus(1);
}
else if (!_startUnityScheduled)
{
_startUnityScheduled = true;
[self performSelector: @selector(startUnity:) withObject: application afterDelay: 0];
}
_didResignActive = false;
}
Build the script XCodePostProcess.cs
to add the code automatically.
- Assign the variable
code
to the code of clearing icon badge in theEditorCode
method. - The method is added through anchored code. Due to Unity version differences, confirm if
[self removeSnapshotViewController];
or[self removeSnapshotView];
is called insideapplicationDidBecomeActive
method, then use the corresponding result in step 3. - Based on the result of step 2, configure
unityAppController.WriteBelow
. - Call
EditorCode
in theOnPostProcessBuild
method. - Check if the built
UnityAppController.mm
has successfully added the code to clear the icon badge.
private static void EditorCode(string filePath)
{
// load UnityAppController.mm
UnityEngine.Debug.Log("EditorCode: " + filePath);
XClass unityAppController = new XClass(filePath + "/Classes/UnityAppController.mm");
//add codes
string codes = "[UIApplication sharedApplication].applicationIconBadgeNumber=0;"; // Add this line
unityAppController.WriteBelow("[self removeSnapshotViewController];", codes); // Add this line
}
Add the callback registration function for Initialize
to INTLAppDelegate.mm
.
FCoreDelegates::ApplicationHasReactivatedDelegate.AddStatic(&ApplicationHasReactivatedDelegate_Handler);
Add functions to INTLAppDelegate.mm
.
static void ApplicationHasReactivatedDelegate_Handler()
{
[UIApplication sharedApplication].applicationIconBadgeNumber =0;
}
Push status
Notification display behavior under different app states:
State | iOS | Android |
---|---|---|
Foreground app | Not displayed | Not displayed |
Background app | Displayed | Displayed |
App closed | Displayed | Displayed |
For iOS 10 or later, userNotificationCenter:
, willPresentNotification:
, withCompletionHandler:
can be modified to display notifications while the app is in the foreground, see the Apple Developer Documentation for more information.
For Samsung devices, users are required to add self-launch permissions for your app in the device settings Settings > Notifications > Hibernation, for push notifications to be received while the app is closed.
For Xiaomi devices, app background permissions must not be restricted in the battery settings, for push notifications to be received while the app is closed. When app memory is cleared on the Xiaomi device, the displayed notification disappears as well.
Callback behavior under different app states:
State | iOS | Android |
---|---|---|
Foreground app | Yes | Yes |
Background app | No | No |
Notification clicked | Yes | No |
Push APIs
- Unity
- Unreal Engine
API | Function |
---|---|
RegisterPush | Register push |
UnregisterPush | Unregister push |
AddLocalNotification | Add local notifications |
ClearLocalNotifications | Clear local notifications |
DeleteLocalNotifications | Delete local notifications |
API | Function |
---|---|
RegisterPush | Register push |
UnregisterPush | Unregister push |
AddLocalNotification | Add local notifications for Android |
AddLocalNotificationIOS | Add local notifications for iOS |
ClearLocalNotifications | Clear local notifications |
DeleteLocalNotifications | Delete local notifications |