OneSignal Integration Guide
For the Lua version of cocos2d-x v3.x - (all other versions)
SDK Version
- ios: 2.12.3
- android: 3.11.2
Integration
First, you must sign up for OneSignal.
Second, Open a terminal and use the following command to install the SDKBOX OneSignal plugin.
$ sdkbox import onesignal
For Android, you need more steps:
- Replace all 3 of instances manifestApplicationId with your package name in AndroidManifest.xml.
Third,
iOS precondition
Android precondition
Important Notice
Please make sure the following settings in your project to make the plugin work well.
Disable App Transport Security
Adding the following entry to the info.plist
file:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
It should look like this:
Disable Bitcode support
You have to turn off Bitcode support. If you don't, cocos2d-x will fail to build.
Set your game requires full screen
If your game doesn't support all screen orientations, you will need to check Requires full screen
in Xcode. If you do not, your app will fail Apple's submission process.
Whitelist canOpenURL function
This setting depends on what plugins are in your project. You may need to add the required entry to the info.plist
, under LSApplicationQueriesSchemes
.
JSON Configuration
SDKBOX Installer will automatically inject a sample configuration to your sdkbox_config.json
, that you have to modify it before you can use it for your own app
"id": [string] App Id
"project_number": [string] Google Project Number (Android only)
Optional
"auto_register": [bool] Enable auto register (iOS only)
"vibrate": [bool] Enable vibrate (Android only)
"sound": [bool] Enable sound (Android only)
"notifications_when_active": [bool] Enable notifications when active (Android only)
Example:
{
"ios": {
"OneSignal":{
"debug":false,
"id":"9a4c9936-62e8-4473-9456-77c50d551870",
"auto_register":true
}
},
"android": {
"OneSignal":{
"debug":false,
"id":"9a4c9936-62e8-4473-9456-77c50d551870",
"project_number":"517386718969",
"vibrate":true,
"sound":true,
"notifications_when_active":false
}
}
}
Usage
Initialize OneSignal
- modify your Lua code to
init()
the plugin. This can be done anyplace, however it must be done before trying to use the plugin's features.
sdkbox.PluginOneSignal:init()
Tag a user based on an app event of your choosing so later you can create segments on onesignal.com to target these users.
sdkbo.PluginOneSignal::sendTag("key", "value");
Retrieve a list of tags that have been set on the user from the OneSignal server.
sdkbo.PluginOneSignal::getTags();
Deletes a tag that was previously set on a user with sendTag
sdkbo.PluginOneSignal::deleteTag("key");
Lets you retrieve the OneSignal user id and push token.
sdkbo.PluginOneSignal::idsAvailable();
You can call this method with false to opt users out of receiving all notifications through OneSignal.
sdkbo.PluginOneSignal::setSubscription(true);
Allows you to send notifications from user to user or schedule ones in the future to be delivered to the current device.
You must build a json string for the API, you can use - rapidjson - picojson
See OneSignal create notification POST call for all options.
Here is a picojson example:
local data = {
contents = {
en = "Test Message"
},
data = {
foo = "bar"
},
include_player_ids = {
"5ea075c5-016d-4f55-891c-3b6c4b393e49",
"4db7cb0f-daca-49d6-b3dd-a96774de9f72",
"33ad9d96-df00-42a2-b5ab-73417f777d42","5ea075c5-016d-4f55-891c-3b6c4b393e49"
}
}
require "json"
sdkbo.PluginOneSignal::postNotification(json.encode(data));
Implement OneSignalListner
- You can implement OneSignalListener if you want to receive callbacks like video finish playing.
sdkbox.PluginOneSignal.setListener(function(args)
dump(args)
local event = args.event
if "onSendTag" == event then
-- args.success, args.key, args.message
elseif "onGetTags" == event then
-- args.jsonString
-- cjson.decode(args.jsonString)
elseif "onIdsAvailable" == event then
-- args.userId, args.pushToken
elseif "onPostNotification" == event then
-- args.success, args.message
elseif "onNotification" == event then
-- args.isActive, args.message, args.additionalData
end
end)
API Reference
Methods
sdkbox.PluginOneSignal:init()
initialize the plugin instance.
sdkbox.PluginOneSignal:setListener(listener)
Set listener to listen for onesignal events
sdkbox.PluginOneSignal:registerForPushNotifications()
Only use if you set "auto_register":false in sdkbox_config.json (iOS only)
--[[
sdkbox.PluginOneSignal.LogLevel.None
sdkbox.PluginOneSignal.LogLevel.Fatal
sdkbox.PluginOneSignal.LogLevel.Error
sdkbox.PluginOneSignal.LogLevel.Warn
sdkbox.PluginOneSignal.LogLevel.Info
sdkbox.PluginOneSignal.LogLevel.Debug
sdkbox.PluginOneSignal.LogLevel.Verbose
]]
sdkbox.PluginOneSignal:setLogLevel(logLevel, visualLogLevel)
Enable logging to help debug if you run into an issue setting up OneSignal. This selector is static so you can call it before OneSignal init. The following options are available with increasingly more information; sdkbox::OneSignalLogNone, sdkbox::OneSignalLogFatal, sdkbox::OneSignalLogError, sdkbox::OneSignalLogWarn, sdkbox::OneSignalLogInfo, sdkbox::OneSignalLogDebug, sdkbox::OneSignalLogVerbose
sdkbox.PluginOneSignal:sendTag(key, value)
Tag a user based on an app event of your choosing so later you can create segments on onesignal.com to target these users.
callback: `onSendTag`
sdkbox.PluginOneSignal:setEmail(email)
Set email
sdkbox.PluginOneSignal:getTags()
Retrieve a list of tags that have been set on the user from the OneSignal server.
callback: `onGetTags`
sdkbox.PluginOneSignal:deleteTag(key)
Deletes a tag that was previously set on a user with sendTag
sdkbox.PluginOneSignal:idsAvailable()
Lets you retrieve the OneSignal user id and the Google registration id. Your handler is called after the device is successfully registered with OneSignal.
callback: `onIdsAvailable`
sdkbox.PluginOneSignal:enableInAppAlertNotification(enable)
By default this is false and notifications will not be shown when the user is in your app, instead the NotificationOpenedHandler is fired. If set to true notifications will be shown as native alert boxes if a notification is received when the user is in your app. The NotificationOpenedHandler is then fired after the alert box is closed.
sdkbox.PluginOneSignal:setSubscription(enable)
You can call this method with false to opt users out of receiving all notifications through OneSignal. You can pass true later to opt users back into notifications.
sdkbox.PluginOneSignal:postNotification(jsonString)
Allows you to send notifications from user to user or schedule ones in the future to be delivered to the current device.
callback: `onPostNotification`
sdkbox.PluginOneSignal:promptLocation()
Prompts the user for location permissions. This allows for geotagging so you can send notifications to users based on location.
Note: Make sure you also have the required location permission in your AndroidManifest.xml.
sdkbox.PluginOneSignal:setRequiresUserPrivacyConsent(enabled)
For GDPR users, your application should call this method before initialization of the SDK. If you pass in true, your application will need to call provideConsent(true) before the OneSignal SDK gets fully initialized.
sdkbox.PluginOneSignal:consentGranted(enabled)
If you set the SDK to require the user's privacy consent, your application can use this method once the user does or doesn't provide privacy consent to use the OneSignal SDK.
sdkbox.PluginOneSignal:requiresUserPrivacyConsent()
You can use this property to check if the OneSignal SDK is waiting for the user to provide privacy consent.
@return [description]
Listeners
onSendTag(success, key, message)
onGetTags(jsonString)
onIdsAvailable(userId, pushToken)
onPostNotification(success, message)
onNotification(isActive, message, additionalData)
onNotificationOpened(message)
onNotificationReceived(message)
Manual Integration
If the SDKBOX Installer fails to complete successfully, it is possible to integrate SDKBOX manually. If the installer complete successfully, please do not complete anymore of this document. It is not necessary.
These steps are listed last in this document on purpose as they are seldom needed. If you find yourself using these steps, please, after completing, double back and re-read the steps above for other integration items.
Manual Integration For iOS
Drag and drop the following frameworks from the plugins/ios folder of the OneSignal
bundle into your Xcode project, check Copy items if needed
when
adding frameworks:
sdkbox.framework
PluginOneSignal.framework
OneSignal.framework
You also need to add the following system frameworks, if you don't already have them:
SystemConfiguration.framework
Copy all source and header files from plugin/luabindings/
to your projects Classes
folder.
Add these same files, that you just copied, to Xcode by either dragging and dropping them into Xcode or by using File -> Add files to....
Manual Integration For Android
SDKBOX supports three different kinds of Android projects command-line, eclipse and Android Studio.
proj.android
will be used as our<project_root>
for command-line and eclipse projectproj.android-studio
will be used as our<project_root>
for Android Studio project.
Copy Files
Copy the everything from plugin/android/libs
folder of this
bundle into your project's
-
If you're using cocos2d-x from source copy the jar files to:
Android command-line:
cocos2d/cocos/platform/android/java/libs
Android Studio:
cocos2d/cocos/platform/android/java/libs cocos2d/cocos/platform/android/libcocos2dx/libs
-
If you're using cocos2d-js or lua copy the jar files to:
Android command-line:
frameworks/cocos2d-x/cocos/platform/android/java/libs
Android Studio:
frameworks/cocos2d-x/cocos/platform/android/java/libs frameworks/cocos2d-x/cocos/platform/android/libcocos2dx/libs
-
If you're using prebuilt cocos2d-x copy the jar files to:
Android command-line:
proj.android/libs
Copy jni libs
Copy and overwrite all the folders from plugin/android/jni
to your <project_root>/jni/
directory.
Edit AndroidManifest.xml
Include the following permissions above the application tag:
<!--Mandatory permissions to receive ads-->
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<permission android:name="__manifestApplicationId__.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="__manifestApplicationId__.permission.C2D_MESSAGE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<!-- START: ShortcutBadger -->
<!--for Samsung-->
<uses-permission android:name="com.sec.android.provider.badge.permission.READ"/>
<uses-permission android:name="com.sec.android.provider.badge.permission.WRITE"/>
<!--for htc-->
<uses-permission android:name="com.htc.launcher.permission.READ_SETTINGS"/>
<uses-permission android:name="com.htc.launcher.permission.UPDATE_SHORTCUT"/>
<!--for sony-->
<uses-permission android:name="com.sonyericsson.home.permission.BROADCAST_BADGE"/>
<!--for apex-->
<uses-permission android:name="com.anddoes.launcher.permission.UPDATE_COUNT"/>
<!--for solid-->
<uses-permission android:name="com.majeur.launcher.permission.UPDATE_BADGE"/>
<!-- End: ShortcutBadger -->
Additionally, you will need to add the Kochava broadcast receiver and the following meta-data tag between the application tags, this is needed for the Google Play referral data capture:
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
<receiver android:name="com.onesignal.GcmBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="__manifestApplicationId__" />
</intent-filter>
</receiver>
<receiver android:name="com.onesignal.NotificationOpenedReceiver" />
<service android:name="com.onesignal.GcmIntentService" />
<service android:name="com.onesignal.SyncService" android:stopWithTask="false" />
<activity android:name="com.onesignal.PermissionsActivity" android:theme="@android:style/Theme.Translucent.NoTitleBar" />
### Edit `Android.mk`
Edit `<project_root>/jni/Android.mk` to:
Add additional requirements to __LOCAL_WHOLE_STATIC_LIBRARIES__:
LOCAL_WHOLE_STATIC_LIBRARIES += PluginOneSignal LOCAL_WHOLE_STATIC_LIBRARIES += sdkbox
Add a call to:
$(call import-add-path,$(LOCAL_PATH))
before any __import-module__ statements.
Add additional __import-module__ statements at the end:
$(call import-module, ./sdkbox) $(call import-module, ./pluginonesignal)
This means that your ordering should look similar to this:
$(call import-add-path,$(LOCAL_PATH)) $(call import-module, ./sdkbox) $(call import-module, ./pluginonesignal)
__Note:__ It is important to make sure these statements are above the existing `$(call import-module,./prebuilt-mk)` statement, if you are using the pre-built libraries.
### Modify `Application.mk` (Cocos2d-x v3.0 to v3.2 only)
Edit `<project_root>/jni/Application.mk` to make sure __APP_STL__ is defined
correctly. If `Application.mk` contains `APP_STL := c++_static`, it should be
changed to:
APP_STL := gnustl_static
Copy all source and header files from `plugin/luabindings/` to your projects `Classes` folder.
Add all `.cpp` files, that you just copied, to `Android.mk` in the __LOCAL_SRC_FILES__ section. Example
LOCAL_SRC_FILES := hellocpp/main.cpp \ ../../Classes/AppDelegate.cpp \ ../../Classes/HelloWorldScene.cpp \ ../../Classes/NewSourceFile.cpp
### Modify __AppActivity.java__
#### Plugin >= 2.4.0.3
1. Find the __AppActivity.java__
```bash
find . -name "AppActivity.java"
- Replace
extends Cocos2dxActivity
withextends com.sdkbox.plugin.SDKBoxActivity
Example of the directory where the AppActivity.java file is located:
cpp
- proj.android/src/org/cocos2dx/cpp/AppActivity.java
- proj.android-studio/app/src/org/cocos2dx/cpp/AppActivity.java
- proj.android/app/src/org/cocos2dx/cpp/AppActivity.java ( from cocos2d-x 3.17)
lua
- frameworks/runtime-src/proj.android/src/org/cocos2dx/lua/AppActivity.java
- frameworks/runtime-src/proj.android-studio/app/src/org/cocos2dx/lua/AppActivity.java
- frameworks/runtime-src/proj.android/app/src/org/cocos2dx/lua/AppActivity.java (from cocos2d-x 3.17)
js
- frameworks/runtime-src/proj.android/src/org/cocos2dx/javascript/AppActivity.java
- frameworks/runtime-src/proj.android/app/src/org/cocos2dx/javascript/AppActivity.java ( from cocos2d-x 3.17)
Plugin < 2.4.0.3
-
If you're using cocos2d-x from source, assuming you are in the proj.android directory, Cocos2dxActivity.java is located:
../../cocos2d-x/cocos/platform/android/java/src/org/cocos2dx/ lib/Cocos2dxActivity.java
-
If you're using the prebuilt cocos2d-x libraries assuming you are in the
proj.android
directory, Cocos2dxActivity.java is located:./src/org/cocos2dx/lib/Cocos2dxActivity.java
Note: When using Cocos2d-x from source, different versions have Cocos2dxActivity.java in a different location. One way to find the location is to look in proj.android/project.properties. Example:
android.library.reference.1=../../cocos2d-x/cocos/platform/android/java
In this case, Cocos2dxActivity.java should be located at:
../../cocos2d-x/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxActivity.java
- Modify Cocos2dxActivity.java to add the following imports:
import android.content.Intent;
import com.sdkbox.plugin.SDKBox;
- Second, modify Cocos2dxActivity.java to edit the
onCreate(final Bundle savedInstanceState)
function to add a call toSDKBox.init(this);
. The placement of this call is important. It must be done after the call toonLoadNativeLibraries();
. Example:
onLoadNativeLibraries();
SDKBox.init(this);
-
Last, we need to insert the proper overrides code. There are a few rules here.
-
If the method listed has not been defined, add it.
-
If the method listed has been defined, add the calls to
SDKBox
in the same existing function.
-
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(!SDKBox.onActivityResult(requestCode, resultCode, data)) {
super.onActivityResult(requestCode, resultCode, data);
}
}
@Override
protected void onStart() {
super.onStart();
SDKBox.onStart();
}
@Override
protected void onStop() {
super.onStop();
SDKBox.onStop();
}
@Override
protected void onResume() {
super.onResume();
SDKBox.onResume();
}
@Override
protected void onPause() {
super.onPause();
SDKBox.onPause();
}
@Override
public void onBackPressed() {
if(!SDKBox.onBackPressed()) {
super.onBackPressed();
}
}
Manual Integration for Google Play Services SDK (dependent library only)
Suggestion
Please try the SDKBOX installer first. It will do all the following step for you automatically.
$ sdkbox import googleplayservices
Modify project.properties
An Android Library Reference for Google Play Services is required. The path will be different depending upon your setup. Also, this is an additional download that does not come as part of a standard install. To install use the sdk installer and choose extras->google play services. Here is an example of what this line could look like:
android.library.reference.1=
../android/sdk.latest/extras/google/google_play_services/libproject/
google-play-services_lib
Note: if you already have an android.library.reference.1
you can add
another by incrementing the number as android.library.reference.2
, etc.
Integration manually
We make a lite version of Google Play Services, the project repo is https://github.com/darkdukey/Google-Play-Service-Lite
Copy Files
Copy the gps
folder from plugin
folder of this bundle into your project's
-
If you're using cocos2d-x from source copy the
gps
folder to:Android command-line:
cocos2d/cocos/platform/android/java/libs
Android Studio:
cocos2d/cocos/platform/android/libcocos2dx/libs
-
If you're using cocos2d-js or lua copy the
gps
folder to:Android command-line:
frameworks/cocos2d-x/cocos/platform/android/java/libs
Android Studio:
frameworks/cocos2d-x/cocos/platform/android/libcocos2dx/libs
-
If you're using prebuilt cocos2d-x copy the
gps
folder to:Android command-line:
<project_root>/libs
Modify files for Eclipse
- Modify project.properties
# For source project
android.library.reference.2=../cocos2d/cocos/platform/android/java/libs/gps/
# Or
# For framework project
android.library.reference.1=libs/gps/
Modify files for Android Studio
1. Modify cocos2d/cocos/platform/android/libcocos2dx/build.gradle
dependencies {
+ compile project(':gps')
compile fileTree(dir: '../java/libs', include: ['*.jar'])
}
2. Modify proj.android-studio/app/project.properties
# Project target.
target=android-14
+android.library.reference.1=../cocos2d/cocos/platform/android/java/libs/gps/
3. Modify proj.android-studio/settings.gradle
project(':libcocos2dx').projectDir = new File(settingsDir, '../cocos2d/cocos/platform/android/libcocos2dx')
include ':your_project_name'
project(':your_project_name').projectDir = new File(settingsDir, 'app')
+
+include ':gps'
+project(':gps').projectDir = new File(settingsDir, '../cocos2d/cocos/platform/android/java/libs/gps')
Proguard (optional)
- Edit
project.properties
to specify aProguard
configuration file. Example:
proguard.config=proguard.cfg
- Edit the file you specified to include the following:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# cocos2d-x
-keep public class org.cocos2dx.** { *; }
-dontwarn org.cocos2dx.**
-keep public class com.chukong.** { *; }
-dontwarn com.chukong.**
# google play service
-keep public class com.google.android.gms.** { public *; }
-dontwarn com.google.android.gms.**
-keep class com.google.protobuf.** { *; }
-dontwarn com.google.protobuf.**
-keep class * extends java.util.ListResourceBundle {
protected Object[][] getContents();
}
-keep public class com.google.android.gms.common.internal.safeparcel.SafeParcelable {
public static final *** NULL;
}
-keepnames @com.google.android.gms.common.annotation.KeepName class *
-keepclassmembernames class * {
@com.google.android.gms.common.annotation.KeepName *;
}
-keepnames class * implements android.os.Parcelable {
public static final ** CREATOR;
}
#sdkbox
-keep public class com.sdkbox.** { *; }
-dontwarn com.sdkbox.**
# onesignal
-dontwarn com.onesignal.**
-keep class com.google.android.gms.common.api.GoogleApiClient {
void connect();
void disconnect();
}
-keep public interface android.app.OnActivityPausedListener {*;}
-keep class com.onesignal.shortcutbadger.impl.AdwHomeBadger { <init>(...); }
-keep class com.onesignal.shortcutbadger.impl.ApexHomeBadger { <init>(...); }
-keep class com.onesignal.shortcutbadger.impl.AsusHomeLauncher { <init>(...); }
-keep class com.onesignal.shortcutbadger.impl.DefaultBadger { <init>(...); }
-keep class com.onesignal.shortcutbadger.impl.NewHtcHomeBadger { <init>(...); }
-keep class com.onesignal.shortcutbadger.impl.NovaHomeBadger { <init>(...); }
-keep class com.onesignal.shortcutbadger.impl.SolidHomeBadger { <init>(...); }
-keep class com.onesignal.shortcutbadger.impl.SonyHomeBadger { <init>(...); }
-keep class com.onesignal.shortcutbadger.impl.XiaomiHomeBadger { <init>(...); }
Note: Proguard only works with Release builds (i.e cocos run -m release
) debug builds do not invoke Proguard rules.