User Notifications

First open your project from the CrossMobile application and go to Plugins tab. Press the add button in the plugins section.

From the dropdown list under “Use a CrossMobile Plugin” choose Notifications Framework and press Add.

Your active Plugins will be visible in the Plugins section. If you want to remove a plugin press the garbage can icon next to it.

To register your app for push notifications go to the ApplicationDelegate class.

First we will add a method to request authorization.

    private void registerForPushNotifications() {
        UNUserNotificationCenter.currentNotificationCenter()
                .requestAuthorizationWithOptions(UNAuthorizationOptions.Alert | UNAuthorizationOptions.Badge,
                        (aBoolean, nsError) -> {
                            System.out.println("Permission granted: " + aBoolean);
                        });
    }

Then you add a method to get notification settings and call it if authorization was granted. Check authorization status and if UNAuthorizationStatus.Authorized get shared Application and Register for remote notifications with “UIApplication.sharedApplication().registerForRemoteNotifications();”

    private void registerForPushNotifications() {
        UNUserNotificationCenter.currentNotificationCenter()
                .requestAuthorizationWithOptions(UNAuthorizationOptions.Alert | UNAuthorizationOptions.Badge,
                        (aBoolean, nsError) -> {
                            System.out.println("Permission granted: " + aBoolean);
                            if(!aBoolean)
                                return;
                            getNotificationSettings();
                        });
    }

    private void getNotificationSettings(){
        UNUserNotificationCenter.currentNotificationCenter().getNotificationSettingsWithCompletionHandler(
                settings -> {
                    if(settings.authorizationStatus() != UNAuthorizationStatus.Authorized)
                        return;
                    UIApplication.sharedApplication().registerForRemoteNotifications();
                });
    }

Override didRegisterForRemoteNotificationsWithDeviceToken and didFailToRegisterForRemoteNotificationsWithError to get the result.

If registration was successful didRegisterForRemoteNotificationsWithDeviceToken will be called. from there you can get the device token and send to the application backend server.

If registration was not successful didFailToRegisterForRemoteNotificationsWithError wiil be called. from there you can handle the error.

    @Override
    public void didRegisterForRemoteNotificationsWithDeviceToken(UIApplication app, NSData deviceToken) {
        String token = new String(deviceToken.bytes());
        System.out.println(token);
    }

    @Override
    public void didFailToRegisterForRemoteNotificationsWithError(UIApplication app, NSError error) {
        System.out.println("Failed to register: " + error);
    }
}

To handle received notification’s data, override didReceiveRemoteNotification. All notification’s data will be in the userinfo Map.

    @Override
    public void didReceiveRemoteNotification(UIApplication app, Map<String, Object> userinfo) {
        System.out.println(userinfo.get("body"));
    }

ApplicationDelegate.java

public class ApplicationDelegate implements UIApplicationDelegate {

    private UIWindow window;

    @Override
    public boolean didFinishLaunchingWithOptions(UIApplication app, Map<String, Object> launchOptions) {
        window = new UIWindow(UIScreen.mainScreen().bounds());
        window.setRootViewController(new ViewController());
        window.makeKeyAndVisible();
        registerForPushNotifications();
        return true;
    }

    private void registerForPushNotifications() {
        UNUserNotificationCenter.currentNotificationCenter()
                .requestAuthorizationWithOptions(UNAuthorizationOptions.Alert | UNAuthorizationOptions.Badge,
                        (aBoolean, nsError) -> {
                            System.out.println("Permission granted: " + aBoolean);
                            if(!aBoolean)
                                return;
                            getNotificationSettings();
                        });
    }

    private void getNotificationSettings(){
        UNUserNotificationCenter.currentNotificationCenter().getNotificationSettingsWithCompletionHandler(
                settings -> {
                    if(settings.authorizationStatus() != UNAuthorizationStatus.Authorized)
                        return;
                    UIApplication.sharedApplication().registerForRemoteNotifications();
                });
    }

    @Override
    public void didRegisterForRemoteNotificationsWithDeviceToken(UIApplication app, NSData deviceToken) {
        String token = new String(deviceToken.bytes());
        System.out.println(token);
    }

    @Override
    public void didFailToRegisterForRemoteNotificationsWithError(UIApplication app, NSError error) {
        System.out.println("Failed to register: " + error);
    }
    
    @Override
    public void didReceiveRemoteNotification(UIApplication app, Map<String, Object> userinfo) {
        System.out.println(userinfo.get("body"));
    }
    
    @Override
    public void didReceiveRemoteNotification(UIApplication app, Map<String, Object> userinfo) {
        System.out.println(userinfo.get("body"));
    }
}

For push notifications on Android, CrossMobile Framework uses FireBase

To enable FireBase on your CrossMobile Project you have to edit the gradle script by hand.

The gradle Script is located in the projects root directory.
if it’s not there build your project for android and CrossMobile will generate it

Open build.gradle go at the top and add “classpath ‘com.google.gms:google-services:4.0.1’” under dependencies

buildscript {
    repositories {
        mavenCentral()
        mavenLocal()
        google()
        jcenter()
        maven {
            url 'https://mvn.crossmobile.org/content/repositories/crossmobile/'
        }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.0'
        classpath 'com.google.gms:google-services:4.0.1'
    }
}

and at the bottom of the script add “apply plugin: ‘com.google.gms.google-services’”

dependencies {
    implementation 'com.android.support:multidex:1.0.3'
}
apply plugin: 'com.google.gms.google-services'

the build.gradle script will look like this:

/****************************************************************
 *                                                              *
 * This File is Generated by the CrossMobile build system once. *
 * After creation, CrossMobile will not change this script.     *
 *                                                              *
 * If you delete this file, it will be recreated the next time  *
 * the build system will be affective.                          *
 *                                                              *
 *            *************************************             *
 *            * Change this file at your own risk *             *
 *            *************************************             *
 *                                                              *
 *                                                              *
 * You can find the CrossMobile Framework here:                 *
 * https://crossmobile.tech/                                    *
 *                                                              *
 ****************************************************************/

buildscript {
    repositories {
        mavenCentral()
        mavenLocal()
        google()
        jcenter()
        maven {
            url 'https://mvn.crossmobile.org/content/repositories/crossmobile/'
        }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.0'
        classpath 'com.google.gms:google-services:4.0.1'
    }
}

allprojects {
    repositories {
        mavenCentral()
        mavenLocal()
        google()
        jcenter()
    }
    buildDir = "target/app/build/"
}

apply plugin: 'com.android.application'
apply from: 'target/app/crossmobile.gradle'

def localProperties = new Properties()
file("local.properties").withInputStream {
    stream -> localProperties.load(stream)
}

android {
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    compileSdkVersion 26
    buildToolsVersion "27.0.3"


    dexOptions {
        maxProcessCount 4
        javaMaxHeapSize "3g"
    }

    defaultConfig {
        applicationId appId
        
        minSdkVersion 15
        targetSdkVersion 25

        multiDexEnabled true
    }

    signingConfigs {
        release {
            if (localProperties['key.store'])
                storeFile file(localProperties['key.store'])
            storePassword localProperties['key.store.password']
            keyAlias localProperties['key.alias']
            keyPassword localProperties['key.alias.password']
        }
    }

    buildTypes {
        release {
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            sourceSets {
                main {
                    manifest.srcFile 'target/app/AndroidManifest.xml'
                    java.srcDirs('src/main/java', 'target/generated-sources', 'target/app/gen/main', 'target/generated-sources/annotations')
                    res.srcDirs = ['target/app/res']
                    assets.srcDirs = ['target/app/asset']
                }
            }
            signingConfig signingConfigs.release
        }
        debug {
            sourceSets {
                main {
                    manifest.srcFile 'target/app/AndroidManifest.xml'
                    java.srcDirs('src/main/java', 'target/generated-sources/main', 'target/app/gen/main', 'target/generated-sources/annotations')
                    res.srcDirs = ['target/app/res']
                    assets.srcDirs = ['target/app/asset']
                }
            }
        }
    }
}

dependencies {
    implementation 'com.android.support:multidex:1.0.3'
}
apply plugin: 'com.google.gms.google-services'



Finally go to FireBase Console click Add project



Put your Projects name and click create project.



From FireBase Project OverView click Add Firebase to your Android app



Add your project’s package name and press Register app



Download google-services.json and add it to your projects root directory.



We have already made all the required changes to the gradle script. Press Next.



Finally go to your crossmobile project and build and run to an android device to finish project registration.



You can now send push notifications to your Android app Through Firebase