Windows Phone Guide

Windows Phone Guide

Supported platforms: Windows Phone 8.1 Silverlight

External libraries: Newtonsoft.Json

Netmera SDK supports offline mode: if network is not available, then events will be stored in local cache and processed as soon as network is available.

All methods that return result (except simple ones) are asynchronous, so you will get Task<T> as a result.

1. Initial Setup

1.1- Create new Windows Phone Silverlight 8.1 project

windows phone

1.2- Add reference to Netmera.dll (for existing or new create project)
1.3- Add reference to Newtonsoft.Json using NuGet

wp2

1.4- Create new application using Microsoft live developer console

To setup push notifications you need to provide package security number (PSN) and client secret in Admin panel:
1. Create new application – https://account.live.com/developers/applications
2. Open your Netmera account and open the Netmera application that you want to send push notifications. Open Settings page of your Netmera app. Provide required info to the windows phone section :

wp3

To start working with Netmera SDK you need to initialize it with API key and additional parameters in the app:

2. Initialization 

You should provide Netmera SDK Apikey (Not Rest Apikey) in the method below. You can find sdk apikey at overview page of your Netmera application. This method is synchronous.

NetmeraClient.Initialize(PhoneApplicationService.Current,
"YourSdkApikey", new NetmeraInitializationParameters() { EnableDebugMode = true }, RootFrame);

In debug mode you will get logs in Output in Visual Studio.
You can later change debug mode:

NetmeraClient.ToggleDebugMode(bool enable) 

Also you can subscribe for log messages:

NetmeraLogger.OnLogMessage += NetmeraLogger_OnLogMessage;

Back To Top

Netmera Push Notification

1- Register for push notifications

Registering for push notifications with tags and custom fields (async method)
NetmeraClient.RegisterForPushNotifications(new NetmeraDeviceDetails()
            {
                CustomFields = new List() { new NetmeraKeyValue() { Key = "key1", Value = "2" } },
                RegistrationId = await GetPushUri(),
                Tags = new List() { "tag1","tag2" }
            });

2- Process push notifications

var notification = NetmeraClient.OnPushNotificationReceived(args)

3- Get registered device details

Getting registered device details (async method)
var r = await NetmeraClient.GetRegisteredDeviceDetails();

4- Get Tags

Getting tags, that were used for registering for push notifications (async method)
var r = await NetmeraClient.GetTags(10, 0);

5- Unregister from push notifications

Unregistering from push notifications with tags (async method)
NetmeraClient.UnregisterFromPushNotifications(new NetmeraDeviceDetails()
           {
                RegistrationId = await GetPushUri(),
                Tags = new List() { "tag1", "tag2" }
            });

6- Get notification details

Getting notification details by notification id (async method)
var response = await NetmeraClient.GetNotification(pushId);

7- Get registration id

Getting registration push id that was used for registering for push notifications
var r = NetmeraClient.GetRegistrationId();

Back To Top

Netmera Event

1- Send Event to Netmera

Send single event to Netmera(async method)
NetmeraClient.LogEvent(new NetmeraEvent() { Name = "test" });
 

2- Send Bulk Events to Netmera

Send list of events (async method)
 NetmeraClient.LogEvents(new List() { new NetmeraEvent() { Name = "test" }, new NetmeraEvent() { Name = "test1" } });

Back To Top

Windows Phone API

iOS Guide

iOS Guide

An Overview

Netmera is a cloud based Platform as a Service—PaaS—that provides iOS developers with an intuitive computing platform and iOS solution stacks optimized for mobile applications. On signing up to Netmera, you are provided a user account and the tools needed to develop/customize mobile apps for your diverse application ideas. Your Netmera account allows you to accommodate multiple apps simultaneously and with Netmera, you:

  • Are spared the need to write server codes

  • Do not need to maintain servers

  • Get a prepared SDK which needs minimal configurations and

  • Get Access to API data store

Finally, this is a detailed user guide drafted to help you understand Netmera’s tools and features, as well as integrate them into your mobile app development procedures.

Setup

To start with Netmera, you have to first download the iOS SDK files and configure them on your Xcode workspace. You can learn about that by clicking the “Need Help? Quickstart” button under the overview page of your application. When this is done, return back to this guide to complete your processes.

Initialization

The next step is to initialize your application, using your specific API key. This initialization is done with the following code block (It is recommended that code block should be written in the delegate method “application:didFinishLaunchingWithOptions:”)

[Netmera setApiKey:@"your_apikey"];
Getting Installation Id

In order to get the installation id of the device,  you can use the following code block:

NSString *iid = [Netmera getInstallationId];
Set a Global Timeout Interval

You should also note that Netmera gives you the option to set a timeout interval on all requests for Netmera’s SDK. The default timeout is 60 seconds and this can be activated or changed to suit your needs by simply using the class method: setRequestGlobalTimeout: of Netmera. It can be done with the following code block

[Netmera setGlobalRequestTimeout:30];

Back To Top

Netmera Push Notification

Steps for Sending Your First Push Notification via Netmera

Step 1: Creating a Push Notification Certificate

Please follow the steps that are explained in the Apple’s App Distribution Guide, within the section named “Configuring Push Notifications”. You can find the resources here:

NOTE: In the last step (Installing Client SSL Signing Identity on the Server), you should export your certificate in .p12 format. Step 2: Upload Certificate to Netmera

You have created your APNS Certificate, and exported it as .p12 file. You can now upload the certificate to Netmera. Please go into “Settings” tab of your Netmera application in the Netmera panel, and upload your certificate and it’s password to one of the relevant sections—Development or Production. here is the screenshot of the related section of Netmera panel.

image_ios_tutorial_5

Step 3: Registering Device

By default, just by drag&dropping Netmera iOS SDK to your project and adding your Netmera api key into NetmeraSettings.plist file, SDK will handle all registration process to receive standard and rich push notifications.

If you want to monitor push registration process, you can implement two delegate methods which are stated below in your AppDelegate class:

/**
     * didRegisterForRemoteNotificationsWithDeviceToken method gives you a unique deviceToken that you will use it to address your notification while sending.
     */
    - (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
        // The device is permitted to receive push notifications.
    }

    /**
     * If customer disables push notifications or something else go wrong didFailToRegisterForRemoteNotificationsWithError notifies you.
     */
    - (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err {
        NSLog(@"Registration failed. Reason: %@", err.localizedDescription);
    }

3.1. Registering With Tags

You can register the devices to diverse tags by using the NMDeviceDetail class objects. These tags can be used to target the devices that will receive push notifications. The code below demonstrates process of registering to “News, and Sports” tags:

NMDeviceDetail *deviceDetail = [[NMDeviceDetail alloc] init];
    [deviceDetail addTags:@[@"News", @"Sports"]];

    [NMPushManager registerWithDeviceDetail:deviceDetail completionHandler:^(BOOL deviceDidRegister, NSError *error) {
        if (!error)
            NSLog(@"The device is registered successfully.");
        else
            NSLog(@"Error occurred. Reason: %@", error.localizedDescription);
    }];

Note that, if a device has been registered to some tags before, these new tags will be added to the previously registered tags. The code block below shows the process of adding a new tag called “Tech”.

[deviceDetail addTag:@"Tech"];

[NMPushManager registerWithDeviceDetail:deviceDetail completionHandler:^(BOOL deviceDidRegister, NSError *error) {
    if (!error)
        NSLog(@"The device is registered successfully.");
    else
        NSLog(@"Error occurred. Reason: %@", error.localizedDescription);
}];

The device is now registered to Sports, News, and Tech tags. If you use the following code instead of addTag: or addTags: methods:

//used in order to override previously registered tags 
[deviceDetail overrideTagsWithNewTags:@[@"Tech"]];

Previously-registered tags are removed and device would be only registered to only “Tech” tag.

3.2. Push Notifications and Custom Key-Value Pairs

You can also set custom key-value pairs over NMDeviceDetail object when registering a device. Therefore, if a push notification is sent for the specific custom field(s), the devices registered to them should automatically receive the message.

Custom Fields allows you to store and manage useful information about the device which runs your application. Custom Fields are a way to store user or device specific attributes in a key-value format. For example, by giving your user’s userID as the custom field, you can send push notifications to all devices of specified userIDs.

The developers should be aware of the fact that every time a device is registered with custom field(s), new key-value pair(s) overrides the current ones:

    NMDeviceDetail *deviceDetail = [[NMDeviceDetail alloc] init];
    deviceDetail.customDictionary = [[NSMutableDictionary alloc] init];
    [deviceDetail.customDictionary setObject:@"value1" forKey:@"key1"];
    [deviceDetail.customDictionary setObject:@"value2" forKey:@"key2"];

    [NMPushManager registerWithDeviceDetail:deviceDetail completionHandler:^(BOOL deviceDidRegister, NSError *error) {
        if (!error)
            NSLog(@"The device is registered successfully.");
        else
            NSLog(@"Error occurred. Reason: %@", error.localizedDescription);
    }];

If you just want to add a new key-value pair in the customDictionary instead of overriding it, you should first get custom dictionary information from Netmera, and change it manually:

[NMDeviceDetail getDeviceDetailWithCompletionHandler:^(NMDeviceDetail *deviceDetail, NSError *error) {
        if (!error)
        {NSLog(@"The device detail is obtained successfully. %@",deviceDetail.description);
            [deviceDetail.customDictionary setObject:@"value1" forKey:@"key1"];
            [deviceDetail.customDictionary setObject:@"value2" forKey:@"key2"];

            [NMPushManager registerWithDeviceDetail:deviceDetail completionHandler:^(BOOL deviceDidRegister, NSError *error) {
                if (!error)
                    NSLog(@"The device is registered successfully.");
                else
                    NSLog(@"Error occurred. Reason: %@", error.localizedDescription);
            }];

        }
        else
            NSLog(@"Error occurred. Reason: %@", error.localizedDescription);
    }];

3.3. Unregistering Devices

Netmera provides users with the ability to manage registered devices and tags.

  • Unregister from individual tags:
NMDeviceDetail *deviceDetail = [[NMDeviceDetail alloc] init];
[deviceDetail addTags:@[@"News", @"Tech"]];

[NMPushManager unregisterWithDeviceDetail:deviceDetail completionHandler:^(BOOL deviceDidUnregister, NSError *error) {
    if (!error)
        NSLog(@"The device is unregistered successfully.");
    else
        NSLog(@"Error occurred. Reason: %@", error.localizedDescription);
}];

Using the registration sample above where—News, Sports and Tech groups—were registered on the device, the unregister code block used, delists News and Tech groups from the device.

If Sports group is also unregistered, the device will be registered to only a Broadcast group.

3.4. Unregister From Tags Completely

  • Completely Unregister:

    To completely unregister a device, the method that can be used is unregistering without setting device tags for NMDeviceDetail.

[NMPushManager unregisterWithCompletionHandler:^(BOOL deviceDidUnregister, NSError *error) {
        if (!error)
            NSLog(@"The device is unregistered successfully.");
        else
            NSLog(@"Error occurred. Reason: %@", error.localizedDescription);
}];

3.5. Getting Device Information from Netmera

To get the registered tags or any other registration information currently active on a device, use the code block below:

[NMDeviceDetail getDeviceDetailWithCompletionHandler:^(NMDeviceDetail *deviceDetail, NSError *error) {
if (!error)
NSLog(@"The device detail is obtained successfully.");
else
NSLog(@"Error occurred. Reason: %@", error.localizedDescription);
}];

3.6. Getting the List of Available Tags from Netmera

You can also get all the tags on your application’s token list with the code block below:

[NMPushManager getDeviceTagsWithCompletionHandler:^(NSArray *tags, NSError *error) {
        if (!error)
            NSLog(@"The application registered tags is obtained successfully.");
        else
            NSLog(@"Error occurred. Reason: %@", error.localizedDescription);
}];

3.7. Further Information on Overriding and Adding

Overriding tags or adding them into the tag set is a choice which should be planned before adding them. When all of the tags should change when a user performs a certain action, overriding tags should be used. But otherwise, overriding tags would be considered as a dangerous behavior.

3.7.1. Adding and Overriding Tags

To add tags:

    - (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {

        NMDeviceDetail *deviceDetail = [[NMDeviceDetail alloc] init];
        [deviceDetail addTag:@"Tech"];

        [NMPushManager registerWithDeviceDetail:deviceDetail completionHandler:^(BOOL deviceDidRegister, NSError *error) {
            if (!error)
                NSLog(@"The device is registered successfully.");
            else
                NSLog(@"Error occurred. Reason: %@", error.localizedDescription);
        }];

This piece of code adds “Tech” tag in the on the device.

To override tags:

    - (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {

        NMDeviceDetail *deviceDetail = [[NMDeviceDetail alloc] init];
        [deviceDetail overrideTagsWithNewTags:@[@"Tech"]];

        [NMPushManager registerWithDeviceDetail:deviceDetail completionHandler:^(BOOL deviceDidRegister, NSError *error) {
            if (!error)
                NSLog(@"The device is registered successfully.");
            else
                NSLog(@"Error occurred. Reason: %@", error.localizedDescription);
        }];

This piece of code clears all of the tags on the device and adds @“Tech” tag on the device.

3.7.2. Adding and Overriding Custom Fields

To add custom fields:

    [NMDeviceDetail getDeviceDetailWithCompletionHandler:^(NMDeviceDetail *deviceDetail, NSError *error) {
        if (!error)
        {NSLog(@"The device detail is obtained successfully. %@",deviceDetail.description);
            [deviceDetail.customDictionary setObject:@"value1" forKey:@"key1"];
            [deviceDetail.customDictionary setObject:@"value2" forKey:@"key2"];

            [NMPushManager registerWithDeviceDetail:deviceDetail completionHandler:^(BOOL deviceDidRegister, NSError *error) {
                if (!error)
                    NSLog(@"The device is registered successfully.");
                else
                    NSLog(@"Error occurred. Reason: %@", error.localizedDescription);
            }];

        }
        else
            NSLog(@"Error occurred. Reason: %@", error.localizedDescription);
    }];

This piece of code adds key1:value1 and key2:value2 key-value pairs in the “Custom Dictionary” of the NMDeviceDetail.

To override custom fields:

    NMDeviceDetail *deviceDetail = [[NMDeviceDetail alloc] init];
    deviceDetail.customDictionary = [[NSMutableDictionary alloc] init];
    [deviceDetail.customDictionary setObject:@"value1" forKey:@"key1"];
    [deviceDetail.customDictionary setObject:@"value2" forKey:@"key2"];

    [NMPushManager registerWithDeviceDetail:deviceDetail completionHandler:^(BOOL deviceDidRegister, NSError *error) {
        if (!error)
            NSLog(@"The device is registered successfully.");
        else
            NSLog(@"Error occurred. Reason: %@", error.localizedDescription);
    }];

This piece of code clears the customDictionary of the device detail and adds key1:value1 and key2:value2 key-value pairs in the “Custom Dictionary” of the NMDeviceDetail.

Step 4: Handling Push Notifications

Handling push notifications can be done easily with NMPushManagerDelegate Protocol. Rich Push Notifications and Interactive Push Notifications are handled automatically by the SDK. However if you want to handle push notifications manually; for example if you want to display a standard push notification while the application is in foreground or present the rich push inbox in another view, you should override the delegate methods of the NMPushManagerDelegate Protocol.

Before getting into the NMPushManagerDelegate Protocol, let’s see how Netmera SDK handles push notifications in default:

a. Standard Push Notifications

  • When Application is Closed or in Background:

    Push is received normally. User may open the application by sliding the notification.

  • When Application is in Foreground:

    Nothing happens unless you add code to manually handle standard push notifications which is received in foreground.

b. Rich Push Notifications

  • When Application is Closed or in Background:

    Push is received normally. User may open the application by sliding the notification. When user opens the application, NMPushInbox is shown automatically(modally).

  • When Application is in Foreground:

    NMPushInbox is shown automatically(modally).

c. Interactive Push Notifications

  • When Application is Closed or in Background:

    Push is received normally. User interacts with the application by selecting one of the two choices which are presented in the notification (by sliding the notification to left). Application can take different actions based on the action of the user.

  • When Application is in Foreground:

    The title, text and buttons of the interactive push notification is presented in an UIAlertView. User interacts with the application by selecting one of the two choices which are presented in the UIAlertView. Application can take different actions based on the action of the user.

IMPORTANT NOTE: Currently, if a push notification sent from Netmera is received, default remote notification delegate methods are also called in addition to NMPushManagerDelegate protocol methods. This behavior will be changed in the next major release! If the push notification is sent via Netmera, only NMPushManagerDelegate methods will be called. Therefore, you should update your code and start to use NMPushManagerDelegate methods to manage push notifications coming from Netmera.

Following are the methods and their explanations:

/**
 *  Called whenever a push notification is received. This method will NOT be called if didReceivePush:appState:fetchCompletionHandler: method is implemented.
 *
 *  @param push Push object that is received. It may be an NMPushObject or an NMRichPushObject. You can check via type property of NMPushObject class.
 *  @param state An enum value that describes the state when app has received given push notification. For possible values, see NMAppState.
 *
 *  @note You can implement this method instead of didReceivePush:appState:fetchCompletionHandler: if you do not enable "remote-notification" background mode.
 */
- (void)didReceivePush:(NMPushObject*)push appState:(NMAppState)state;

/**
 * @brief Called whenever a push notification is received. This method overrides didReceivePush:appState: method.
 *
 * @param push Push object that is received. It may be an NMPushObject or an NMRichPushObject. You can check via type property of NMPushObject class.
 * @param state An enum value that describes the state when app has received given push notification. For possible values, see NMAppState.
 * @param completionHandler You should call the completionHandler as soon as you're finished your task, so the system can accurately estimate its power and data cost.
 *
 * @note You should implement this method if you enable "remote-notification" background mode.
 */
- (void)didReceivePush:(NMPushObject*)push appState:(NMAppState)state fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler;

/**
 * @brief Called when your app has been activated by the user via selecting an action from an interactive push notification. You can check push.actionIdentifier value to get action identifier of the touched action button.
 *
 * @param push Push object that is received. You can get parameters set to the action from Netmera panel via push.actionParams property.
 * @param state An enum value that describes the state when app has received given push notification. For possible values, see NMAppState.
 * @param completionHandler You should call the completion handler as soon as you've finished handling the action.
 *
 * @note You should implement this method if you are using interactive notifications in your application.
 */
- (void)handleActionForPush:(NMPushObject*)push appState:(NMAppState)state completionHandler:(void(^)())completionHandler;

/**
 * Method that asks whether received rich push notification should be presented by Netmera SDK automatically.
 * @note If you do NOT implement this method, SDK will automatically present received rich push notifications considering preferences set in NetmeraSettings.plist file. You should implement this method and return NO if you want to handle presentation of received rich push notications yourself.
 * @param richPush Rich push object that is received.
 * @return A boolean value which determines if given rich push should be presented by SDK automatically.
 */
- (BOOL)shouldPresentRichPush:(NMRichPushObject*)richPush;

/**
 *  If an interactive push is received when app is foreground, SDK present an alert containing action buttons to user by default. To disable this, implement this method and return NO.
 *
 *  @param push Received interactive push notification.
 *
 *  @return Boolean value to determine if SDK should automatically present an alert.
 */
- (BOOL)shouldPresentInteractivePushInForeground:(NMPushObject*)push;
a. Below is a piece of code which is needed to display standard push notifications in foreground:

- (void)didReceivePush:(NMPushObject*)push appState:(NMAppState)state
{
    if(push.type == NMNotificationTypeStandard && state ==  NMAppStateWasInForeground)
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Push Notification"
                                                            message:[push alertText]
                                                           delegate:nil
                                                  cancelButtonTitle:@"OK"
                                                  otherButtonTitles:nil];
        [alertView show];

    }

}

b. Handling interactive push notifications which contain action parameters requires the implementation of another delegate method, Below is a simple implementation of this delegate method.

/**
 * @brief Called when your app has been activated by the user via selecting an action from an interactive push notification. You can check push.actionIdentifier value to get action identifier of the touched action button.
 *
 * @param push Push object that is received. You can get parameters set to the action from Netmera panel via push.actionParams property.
 * @param state An enum value that describes the state when app has received given push notification. For possible values, see NMAppState.
 * @param completionHandler You should call the completion handler as soon as you've finished handling the action.
 *
 * @note You should implement this method if you are using interactive notifications in your application.
 */
- (void)handleActionForPush:(NMPushObject *)push appState:(NMAppState)state completionHandler:(void (^)())completionHandler
{
    //Check action identifier
    if([push.actionIdentifier isEqualToString:@"AcceptButton"])
    {
        //TODO: Show information about accepted content.
    }
    else if([push.actionIdentifier isEqualToString:@"DeclineButton"])
    {
        //TODO: Send decline request to server.
    }
    else if([push.actionIdentifier isEqualToString:@"ReplyButton"])
    {
        //TODO: Open mail reply screen.
    }
    else if([push.actionIdentifier isEqualToString:@"MarkAsReadButton"])
    {
        //TODO: Send mark as read request to server.
    }

    //Here you could get parameters related to selected action which are set in Netmera panel using push.actionParams property

    NSLog(@"Action Parameters : %@",push.actionParams);

    //You should always call completionHandler when you are finished.
    completionHandler();
}

Action parameters helps you to answer user’s response to your interactive push notification.

c. You are also free while you are handling Rich Push Notifications :

The “Rich Push Notification” feature is one that provides developers with the ability to send content in an HTML or URL format. This feature allows you to send well designed HTML pages to your app users as push notifications.

The instructions—stated in previous steps—that enable a device to receive push notifications—such as registering etc.—remain valid for utilizing the Rich Push Notification feature. You can easily enable this feature and send HTML themed notifications just by adding Netmera iOS SDK. Then everything is handled by SDK itself automatically.

While the application is on the background or not running, alert text of receiving rich push is displayed as a banner automatically by Apple, again and if you click the push notification, the application opens, you see firstly a loading indicator (it is not be displayed while the application is on foreground, since we do not want to sever application action flow.) and then rich push notification as a webview on the screen. However, while the application is on the foreground, rich push notification is displayed automatically by Netmera iOS SDK when the application is opened, but you can optionally change this action. Therefore, you see first text message as an alert, click the show button and see rich push notification. You can even ignore all rich push notifications coming while the application is only on foreground. This is beneficial while the application has important tasks when the user should not be distracted by any other task, i.e. the user performing purchase process. All these configurations can be adjusted from NetmeraSettings.plist.

Handling Rich Push Notification can be done through:

- (BOOL)shouldPresentRichPush:(NMRichPushObject*)richPush;

delegate method, display the rich push or the rich push inbox manually and return NO to prevent Netmera SDK from automatically displaying the rich push object.

NOTE: By default, when a rich push notification is received, Netmera SDK shows a “RichPushViewController” modally on the currently visible controller. So you don’t need to set a parent controller.

In order for this feature to work appropriately, you need to set the root view controller of your application in your “AppDelegate” class like this:

window.rootViewController = YOUR_ROOT_CONTROLLER;

Note: If you add your rootViewController’s view as a sub view to your window –like, [window addSubview:YOUR_ROOT_CONTROLLER.view]—, RichPushViewController won’t be shown. Step 5: Managing Button Sets For Interactive Push Notifications

Enabling interactive push notifications for your device is very simple. You only need to call [NMPushManager setUserNotificationCategories:] method with an NSSet containing UIUserNotificationCategory objects. Netmera will automatically register the app for given categories, and synchronize Netmera panel with your button sets. Here is a simple example that you can call in any place (application:didFinishLaunchingWithOptions: is the recommended place):

//This check is needed if your application supports iOS 7 or before.
    if([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)])
    {
        //FIRST CATEGORY (Accept/Decline Button Set)
        UIMutableUserNotificationAction *action1 = [[UIMutableUserNotificationAction alloc] init];
        action1.identifier = @"AcceptButton";
        action1.title = @"Accept";
        action1.activationMode = UIUserNotificationActivationModeForeground;

        UIMutableUserNotificationAction *action2 = [[UIMutableUserNotificationAction alloc] init];
        action2.identifier = @"DeclineButton";
        action2.title = @"Decline";
        action2.activationMode = UIUserNotificationActivationModeForeground;
        //To show a destructive button.
        action2.destructive = YES;

        UIMutableUserNotificationCategory *acceptDecline = [[UIMutableUserNotificationCategory alloc] init];
        //This identifier string will be visible in Netmera panel.
        acceptDecline.identifier = @"AcceptDeclineAction";

        //Setting actions for UIUserNotificationActionContextMinimal is enough. SDK will automatically add related action for UIUserNotificationActionContextDefault also.
        //PS: Netmera currently NOT supports having more than two actions. So, you can NOT use different action sets for different contexts.
        [acceptDecline setActions:@[action1, action2] forContext:UIUserNotificationActionContextMinimal];

        //SECOND CATEGORY (Reply/Mark As Read Button Set)
        UIMutableUserNotificationAction *action3 = [[UIMutableUserNotificationAction alloc] init];
        action3.identifier = @"ReplyButton";
        action3.title = @"Reply";
        action3.activationMode = UIUserNotificationActivationModeForeground;

        UIMutableUserNotificationAction *action4 = [[UIMutableUserNotificationAction alloc] init];
        action4.identifier = @"MarkAsReadButton";
        action4.title = @"Mark As Read";
        //This tells that application will not be opened when Mark As Read button is selected.
        //It will only wake the application in background mode.
        action4.activationMode = UIUserNotificationActivationModeBackground;

        UIMutableUserNotificationCategory *mailCategory = [[UIMutableUserNotificationCategory alloc] init];
        mailCategory.identifier = @"MailReplyAction";
        [mailCategory setActions:@[action4, action3] forContext:UIUserNotificationActionContextMinimal];

        //Registers the device to related interactive notification categories.
        [NMPushManager setUserNotificationCategories:[NSSet setWithObjects:acceptDecline, mailCategory, nil]];
    }

Step 6: Getting the Details of the Push Notification

Although the limitation on the maximum amount of data which can be transmitted with a push notification is increased in iOS 8, Netmera does not send the push notification object completely, you should use [NMPushObject fetchPushDetailsWithCompletionHandler:] method and use the data in the completion handler.

Payload information specified as key-values pairs can be with relevant push notification messages, by setting the needed values in the boxes provide for them on the Netmera Create Campaigns screen. This allows you to include additional information to your push notifications while sending them out. You can use push.customParams in the completion handler of the [NMPushObject fetchPushDetailsWithCompletionHandler:] method to access those key-value pairs.

This piece of code ( an override of [NMPushManagerDelegate didReceivePush: appState:] ) can help you to understand when and how to use [NMPushObject fetchPushDetailsWithCompletionHandler:] method:

- (void)didReceivePush:(NMPushObject*)push appState:(NMAppState)state
{
    NSLog(@"Before:");
    NSLog(@"Send Date: %@",push.sendDate.description);
    NSLog(@"Alert Text: %@",push.alertText.description);
    NSLog(@"Event Custom Parameters: %@",push.eventCustomParams.description);
    NSLog(@"Custom Parameters: %@", push.customParams.descriptionInStringsFileFormat);
    NSLog(@"NotificationID: %@",push.notificationId.description);
    NSLog(@"Create Date: %@",push.createDate.description);
    NSLog(@"Expiration Date: %@",push.expirationDate.description);
    NSLog(@"Type: %u",push.type);
    NSLog(@"Push Inbox Status: %u",push.pushInboxStatus);
    NSLog(@"Category:%@",push.category.description);
    NSLog(@"Push Logo URL: %@",push.pushLogoURL.description);
    NSLog(@"Push Inbox Status: %u",push.pushInboxStatus);

    [push fetchPushDetailsWithCompletionHandler:^(NSError *error) {

        if (!error)
        {
            if(push.type == NMNotificationTypeStandard)
            {

                if(state != UIApplicationStateBackground)
                {
                    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Push Notification"
                                                                    message:[push alertText]
                                                                   delegate:nil
                                                          cancelButtonTitle:@"OK"
                                                          otherButtonTitles:nil];
                    [alertView show];
                }
            }

        }
        else
            NSLog(@"Error occurred. Reason: %@", error.localizedDescription);

        NSLog(@"After:");
        NSLog(@"Send Date: %@",push.sendDate.description);
        NSLog(@"Alert Text: %@",push.alertText.description);
        NSLog(@"Event Custom Parameters: %@",push.eventCustomParams.description);
        NSLog(@"Custom Parameters: %@", push.customParams.descriptionInStringsFileFormat);
        NSLog(@"NotificationID: %@",push.notificationId.description);
        NSLog(@"Create Date: %@",push.createDate.description);
        NSLog(@"Expiration Date: %@",push.expirationDate.description);
        NSLog(@"Type: %u",push.type);
        NSLog(@"Push Inbox Status: %u",push.pushInboxStatus);
        NSLog(@"Category:%@",push.category.description);
        NSLog(@"Push Logo URL: %@",push.pushLogoURL.description);
        NSLog(@"Push Inbox Status: %u",push.pushInboxStatus);
    }];

}

Step 7: Push Notification Sounds

Netmera provides you with the features required to send push notifications with particular sounds to devices running your apps. This can be done by enabling the sound feature from the Setup tab of Create Campaign section.

There are three states for “ADD NOTIFICATION SOUND FOR iOS” field, which controls sound feature. These three states are:

  • “Default”: This value enables the phone to play the current default notification sound when receiving the push notification from your application. In this situation, no extra work is needed.

  • “Silence.wav”: Your application does not play any sound when receiving your notification.

  • “your_sound_name”: You can specify any sound to be played when receiving the push notification. To perform this function, you should pay attention to some constraints. One of them is that your sound file should be included in your main bundle. If this condition does not meet, default sound of your phone will be played when receiving the push notification, instead. Another constraint is that you can use just the audio data packaged in an ‘aiff’, ‘wav’ or ‘caf’ file (i.e. your_sound_name.aiff). Last constraint is that you can add at most 30-seconds-length custom sounds. If any sound exceeds 30 seconds, the default sound of your phone will be played instead of your custom one. You can select any sound name in the drop-box menu. All items in the menu are the sound files which extensions satisfy the push sound extensions (.aiff, .wav and .caf).

It is important to note that the states mentioned above are valid or occur when your app is at the background of a devices interface or not currently being run. But if your app is currently being run on a devices interface/display screen, all sent information—such as sound, alerts or payload—will be sent within the user’s info thereby eliminating sounds.

Alternatively, you can also enable notification sounds even if your app is being currently run on the foreground of a device with the “applications: didRecieveRemoteNotification:” method class as shown below:

// You should also check application state if you donot want // to play notification sound two times when your application //is on background.
if (![[notificationSound objectAtIndex:0] isEqual:@"default"]) {
      NSString *notificationSoundName = [notificationSound objectAtIndex:0];
      NSLog(@"Notification sound name : %@", notificationSoundName);
      NSString *notificationSoundType = [notificationSound objectAtIndex:1];
      NSLog(@"Notification sound type : %@", notificationSoundType);
      NSString *notificationSoundPath = [[NSBundle mainBundle] pathForResource:notificationSoundName ofType:notificationSoundType];
      NSURL *notificationSoundURL = [NSURL fileURLWithPath:notificationSoundPath];
      AudioServicesCreateSystemSoundID((__bridge CFURLRef)notificationSoundURL, &_notificationSound); // _notificationSound is a property.
      AudioServicesPlaySystemSound(self.notificationSound);
}

NOTE: All sound names in the drop-box menu are received from your main bundle by Netmera iOS SDK automatically. However, you should pay attention on significant point. After changing or removing a current sound file, and cleaning the project, new built product actually updates its contents (It is valid in case of renaming, it renames sound file correctly, and remove old one). During deployment of product to simulator or any device, XCode somehow does not check or detect renaming, it persists old sound file, but also add newly-renamed file, so there will be 2 different files in the actual product. Therefore, SDK sends both names to Netmera and you will see them in the drop-down menu for push sound files. Both sound names can be used while sending push notifications, it will not crash the application even if it does not exist in the main bundle. In order to remove old sound files from the device or simulator, developer should uninstall application from device/simulator. There is no other way for now. Step 8: Push Inbox for Rich Push Notifications

“Push Inbox” is a feature, which gives app users the opportunity to store and redisplay rich push notifications via an interface in your application. By default, this feature is enabled by the SDK, which means all coming rich push notifications are shown as if they are opened from inbox. In order to disable push inbox feature in your application, you can simply set NO for pushInboxEnabled flag NetmeraSettings.plist or call below method:

[Netmera setPushInboxEnabled:NO];

You can also enable the ability to open Push inbox while a custom action occurs—touch event of a button—by utilizing the call method below:

[NMPushManager presentPushInboxFromController:YOUR_CONTROLLER];

By default, this method presents a modal controller which shows the list of rich push notifications that have been sent to your phone. Additionally, all controllers related to push inbox are open source, so that you can change the default ones or use your custom ones if you like. You can find the related source codes under NetmeraSDK/Resources folder.

Moreover, Push inbox of your application is available when the internet connection is lost, however, you should access to Internet in order to display rich push notifications.

Step 9: Automatic Badge Increment

You can add iOS badges to your application icon when receiving rich push notifications, while plain push notifications do not change badge number. In order to achieve this, you do not need to make any changes in your code. All that is needed is for you to prepare your own rich push notification in the “Campaigns” tab on the Netmera website.

If you like to use a badge, you should activate badge increment in the “Setup” panel of “Create Campaign” section. If your user does not read the incoming rich push, a badge number will be displayed on your application icon.

Current push inbox controller of Netmera IOS SDK also gives your users the opportunity to change badge numbers manually by simply marking received rich push notifications as read, or as unread, or by deleting from push inbox. This feature guarantees that your users will recieve your rich push notifications.

Step 10: Deep linking Mechanism (New Feature for navigation)

Note: You should use Netmera IOS SDK version 2.5 or above for this feature.
Deep linking enables your application to open specific screens upon actions taken from push notifications. To enable deep linking for your application, you should define a custom url scheme specific to your application following these steps:

10.1- Select your project target and navigate “Info” tab.

deeplink_1


10.2- Expand “URL Types title and click + button on the bottom left corner to add a URL Type.


deeplink_2


10.3- Provide a value for “Identifier” field. This can be any value, but the convention is to use a “reverse domain name” as the bundle identifier of your project (i.e. “com.netmera.CustomURLSchemesTestProject”).

deeplink_3


10.4- For “URL Schemes” field, set a lowercase string unique to your application (i.e. the last component of your bundle identifier).

Here is an example deep link pattern which is created from Netmera panel:

yourscheme://yourhost?productId={productId}&productCategory={productCategory}

You can handle above link with the following code snippet:

-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString*)sourceApplication annotation:(id)annotation {
	if (![[url scheme] isEqualToString:@"yourscheme"]) { 
		return NO; 
	} 
	NSURLComponents *components = [NSURLComponents componentsWithString:url.absoluteString];
	//Identifier that indicates which screen to present.
	NSString *deepLinkIdentifier = [components host];
	
	//Array of NSURLQueryItem objects that contains key-value parameter pairs 
	NSArray *params = [components queryItems];
	
	// Here you can decide which screen to present according to deepLinkIdentifier variable, and you can inject sent 
	// parameters to the view controller to be presented either by using key-value coding or manually.
	// 
	//	*
	//	*
	//	*
	return YES; 
}

Step 11: Testing Push Notifications Before Sending

In order to test your push campaigns before sending them to your target users, you can add some of your devices into the test group and simulate your campaign in advance. For this to be implemented, you should just register your application to a custom URL scheme and for that scheme to be used to add the relevant device into the test group with a link that have to be clicked on the device in a received mail from Netmera.

Registering a custom URL scheme is done with the info.plist (By default, projectName-Info.plist) file located in your application's project folder. In XCode, you can edit it directly in "Info" tab of target settings or using info.plist in graphical mode or text mode. Fore more information about "Custom URL Schemes", you can look at "Implementing Custom URL Schemes" title from the following link here.

Below you can see the steps regarding how to register a Custom URL Schemes from XCode "Info" tab of target settings.

Step1: Select your project target and navigate "Info" tab.

URL_Scheme_1

Step2: Expand "URL Types title and click + button on the bottom left corner to add a URL Type.

URL_Scheme_2

Step3: Provide a value for "Identifier" field. This can be any value, but the convention is to use a "reverse domain name" as the bundle identifier of your project (i.e. "com.netmera.CustomURLSchemesTestProject").

URL_Scheme_3

Step4: For "URL Schemes" field, you need to get your application's name from Netmera panel. Open your Netmera application, and take your application's name from URL like this:

Screen-Shot-2014-04-01-at-10.35.01

Then you should write the string "nm{YOUR_APPLICATION_NAME}" into "URL Schemes" field. For this example, the value should be "nmurlschemetest".

Final form of registered URL Scheme should be like this:

URL_Scheme_5

Back To Top

Netmera Event

The intuitiveness of Netmera makes it possible for you to track the behavioral patterns of your app users. Netmera does this by using its Event method class to automatically record the following events:

  • Application installation event

  • Application open events

  • Application close events

  • Events that shows a user’s time duration spent on the application

  • Push notification open events

  • Location change events, both on the foreground and background modes

Also, you can set custom events to track certain actions and events that occur on your application as suits your needs.

In order to accomplish this, the class method “sendEventWithKey:value:” of NetmeraEvent would be called when intended actions such as; Twitter/Facebook share or user sign up etc., occurs.

A Sample code block to show how Netmera event can be set is shown below:

[NMEvent sendEventWithKey:@”TwitterShareEvent” value:your_event_data];

Note: When using the code above, you have to set an NSDictionary instance, for value parameter.

If SDK cannot send events to server at that moment because of a problem such as internet connection loss, your events are cached in an event queue and when the device is finally connected to the internet, events in the queues are then automatically sent to the server.

 [NMEvent sendEventWithKey:@"Your Custom Event Name"
                   value:@{
                   @"category" : @[ @"News", @"Sports", @"Economics" ],
                   @"id" : @"1234567"
               }];

As you can see in this example, “category” key contains multiple values “News”,”Sports” and “Economics”

Back To Top

Netmera Popup

Pop-ups are very helpful in boosting in-app communication with users. They are shown according to user actions such as app opens, specific page views, or other valuable custom actions that you have decided.

Best thing about Netmera pop-up service is that you do not need to change anything in your app to change the message that is displayed. Each time the user opens the app; Netmera SDK will download the latest pop-up contents and display the current message.

Each pop-up notification is related to an event which will trigger pop-up when it is fired by the application. For example, if user opens the app and if there is any pop-up triggered by this open event, this pop-up will be available to be presented to user. However, Netmera does not show pop-ups automatically after these events. Instead, it stores currently available pop-ups in a structured way, so that you can achieve and present them to user whenever and wherever you want.

Step 1: Triggering Popups

There are two techniques that you can use in iOS SDK to get pop-ups triggered by their relevant event.

First one is to call addObserver:forEventKey:usingBlock: and removeObserver:forEventKey: methods.

The logic of these methods are similar to the ones featuring in “NSNotificationCenter” class. Whatever events you want to listen for popups, you should give the name of the event as parameter. (For Open app events, you should use ‘NMAppOpenEvent’ constant.) If you give this parameter nil, you will be informed whenever an event fires.

You should also provide an observer object, usually a UIViewController object, for tracking the event. This object is important when you want to remove the relevant observer to track the event. When an event fires, if you listen to it, your block is executed with the triggered popups binded to it. You can see it the argument signature of the block parameter. (void(^NMPopupTriggerResult)(NSMutableArray *triggeredPopups))

To add an observer for one of your custom events in a controller, you should use the following code.

[NMPopupManager addObserver:self forEventKey:YOUR_EVENT_KEY usingBlock:^(NSMutableArray *triggeredPopups) {
     // You can continue to presentation procedure or anything else regarding popup object.
}];

To add an observer for popups that are related to all different types of events, use the following:

[NMPopupManager addObserverForAllEvents:self usingBlock:^(NSMutableArray *triggeredPopups) {
     // You can continue to presentation procedure or anything else regarding popup object.
}];

To remove the registered observer, you should use the following code. It is recommended that if you add a controller object as an observer, you should at least call this method in ‘dealloc’ implementation.

[NMPopupManager removeObserver:self forEventKey:YOUR_EVENT_KEY];

To remove observer for all events, use the following:

[NMPopupManager removeObserverForAllEvents:self];

 

The second technique is to call the methods named getTriggeredPopups: and getTriggeredPopupsWithEventKey:. They return an NSArray object that contains available NMPopupObject objects. From the list, you should choose which pop up you want to show. You can define more than one pop up for each event and that is why these methods return list instead of one NMPopup object.

By using these methods, you can gather triggered pop-ups and present it to user whenever you want.

In case you want to get pop-ups which have been triggered by a specific event, you should use following code.

NSArray *popupList = [NMPopupManager getTriggeredPopupsWithEventKey:YOUR_EVENT_KEY];
NMPopupObject *popup = [popupList objectAtIndex:INDEX];
// After that, you can continue to presentation procedure

Whereas, if you wish to get all triggered pop-ups without regarding by which event it is triggered, you can use getTriggeredPopups method.

Step 2: Displaying Popups

Presenting pop-ups onto screen is very simple. After you get the NMPopupObject object you want to show using one of the get methods, you just call one of the following to present pop-up on screen.

[NMPopupManager presentPopup:POPUP_OBJECT];

This method presents given pop-up on top of the currently visible controller. Pop-up is shown as a modal controller – on full screen – using a fancy poppy animation.

[NMPopupManager presentPopup:POPUP_OBJECT fromController:PARENT_CONTROLLER];

This method presents given pop-up on top of the given view controller.

Additionally, if you need you show your popup in another custom way, you could add a UIWebView in your view hierarchy, and then you can load your pop-up to this webview using following line of code:

NMPopupObject *popup = [[NMPopupManager getTriggeredPopups] objectAtIndex:INDEX];
[popup presentInWebView:WEBVIEW_OBJECT];

Back To Top

Netmera Location Manager

The NMLocationManager is a feature that enables developers to track locations of devices, so these devices can take advantage of location based push notifications. With the NMLocationManager, you do not need to manually track the location of devices because the service automatically updates device locations through your app.

The Netmera Location Manager helps developers create push notification campaigns that take the location of a device into consideration. It also incorporates a time interval notification mechanism that send automated push messages to devices in a specified location, at specific time durations.

 Activating Location Tracking

By default, Netmera tracks users’ location changes using Apple’s significant-location tracking service, which provides a low-power location service for location updates. (Details can be found here)
However, if you need a more precise location tracking, you could start a location manager using NMLocationManager to track location with desired configuration.

Getting Location Authorization on iOS8 Devices

Core Location service API has received a major change about getting users’ permission in iOS 8. There are two authorisation types:

  • AlwaysAuthorization :

    Requests permission to use location services always (when app is either in background or foreground or not running).

  • WhenInUseAuthorization :

    Requests permission to use location services while the app is in the foreground.

There is a simple step that you must do in order to make Netmera get location updates in iOS 8 devices. You only have to put one of the NSLocationAlwaysUsageDescription or NSLocationWhenInUseUsageDescription keys with proper description text strings. These texts will be prompted to user when requesting location permission.

Netmera will automatically call needed authorization request methods by checking the key that you put to your application’s Info.plist file.

Note:NSLocationAlwaysUsageDescription key will have precedence over NSLocationWhenInUseUsageDescription key. In other words, if you give both keys in Info.plist file, users will be asked to give always authorization.

Developers can easily incorporate the Location services on apps by using the following steps:

Step 1: Configure NMLocationManager

Developers are given free rein to customize feature parameters—distanceFilter and desiredAccuracy—as they wish. Apple constants and double metric values can also be utilized. This customization is optional. If developer does not set any value for these parameters, default values (kCLLocationAccuracyHundredMeters for distanceAccuracy and 10.0 meters for distanceFilter) will be used. Below is a sample code block explaining/showing the process:

[NMLocationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
[NMLocationManager setDistanceFilter:20.0];

Step 2: Activate NMLocationManager

The next step is initializing NMLocationManager. This is done by passing NMLocationManager class with the “startLocationTracking” call method, a shown below:

[NMLocationManager startLocationTracking];

In order to track location when the application is on background, you must enable “Location updates” background mode for your application. Then, our location service will be informed for position changes of the device.

Step 3: Stop NMLocationManager

Netmera allows you to control all aspect of the location service, and you can easily stop the service by calling the “stopLocationTracking” method, as shown below:

[NMLocationManager stopLocationTracking];
Disabling Location Tracking

If you want to totally disable default location tracking for your application, you can set NO value for “SignificantLocationChangeTrackingEnabled” key in NetmeraSettings.plist  or disable it using the following line of code (The first way is recommended.):

[Netmera setSignificantLocationChangeTrackingEnabled:NO];

Preferred position of calling this method is at just after calling application:didFinishLaunchingWithOptions: delegate method. By this way, your application will not ask user for location tracking permissions.

You can also call it anywhere in your app lifecycle – e.g. put an option to enable/disable location tracking from settings menu of your application –, but in this case, users will be asked for location permission at application startup.

Back To Top

iOS API

Android Guide

Android Guide

Netmera is a cloud platform (PaaS & App engagement platform) optimized for mobile applications. Netmera offers push notification services and detailed app analytic service. With simple APIs and mobile SDKs, you can send and retrieve push notifications easily by targeting your customers based on their behaviors, properties and responses.


If you don’t have Netmera SDK installed on your development environment yet, please first visit the following page:
https://cp.netmera.com/nm/admin/tutorial

Initialization

To be able to use Netmera services, you must initialize your application with your API key. An initialization without API key will cause an Exception.

This initialization can be done with the following instructions:

There are 2 methods to initialize the application. Using only one of them is suitable for initialization.

1- Initialization Using netmera.properties File

You need to add netmera.properties file to assets folder of the application. Here is an example properties file:
Note: You shouldn’t use quotation mark for values. (correct format: googleProjectNumber=1112223334444)

#Netmera API key
apiKey=Your api key here
#Project number obtained from Google Developers Console
googleProjectNumber=Your Google project number here
#Push activity class name with full package name
pushActivityClassName=com.example.netmera.PushActivity
# Log level must be one of the following: ERROR, WARNING, INFO, DEBUG, VERBOSE. Default is ERROR.
logLevel=VERBOSE
# Is location service active? Default is false
locationEnabled=false
# Is exception reporting active? Default is true
exceptionReportingEnabled=false
# Is push inbox enabled? Default is false
pushInboxEnabled=false
# Is pop-up retrieval on start up active? If you are using pop up, please activate this.
# Default is false
popupRetrievalOnStartupEnabled=true

In this file, you have to set a Netmera SDK Api key. Otherwise, you will get an exception. After creating the file, call Netmera.init(Application) method. You should call Netmera.init(Application) method from the class which extends Application (android.app.Application) which you also set in AndroidManifest.xml file.

package my.package.namespace;
import android.app.Application;

public class YourAppClass extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        Netmera.init(this);
    }
}

Don’t forget to add name of this Application class in AndroidManifest.xml file like below

<application android:name="my.package.namespace.YourAppClass"
.........
.........>
...</application>

Please check Initialization Notes written below.

2- Inialization Using NetmeraProperties Class

You can initialize Netmera from code and without netmera.properties file under assets. You just need to build a NetmeraProperties instance and give it to proper Netmera.init method in your Application class.

package my.package.namespace;
import android.app.Application;

public class YourAppClass extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        NetmeraProperties prop = new NetmeraProperties.Builder("Netmera API Key")
            .googleProjectNumber("Google Project Number")
            .pushActivityClass(PushActivity.class)
            .exceptionReportingEnabled(false)
            .logLevel(LogLevel.VERBOSE)
            .locationTrackingEnabled(true)
            .pushInboxEnabled(false)
            .popupEnabled(true)
            .build();
            Netmera.init(this, prop);
    }
}

If you need to be informed about the result of the init method, you may add a listener to the method above as shown below.

Netmera.init(TestApp.this, prop, new NetmeraCallback<Void>() {

        @Override
        public void onSuccess(Void v) {
             Log.i(“Netmera”, “Netmera initialized successfully!”);   
        }

        @Override
        public void onFail(NetmeraException e) {
            e.printStackTrace();
        }
    });
Initialization Notes

If you set a Google project number and push activity class, default push registration will be done automatically. Google project number can be obtained from Google APIs console. For more information, please see our Netmera Push Notification Guide page. Push activity class name must include full package name.

You may want to see inner Netmera logs to track what Netmera does or if you use Netmera’s Logging class to log your app, you need to set a log level to see logs. Otherwise, you can see only ERROR level logs. To set log level, you can use netmera.properties file or NetmeraProperties class as shown above. For more info about log level, please visit API doc.

You can enable location tracking from netmera.properties or NetmeraProperties class as shown above. To be able to start tracking, you need some extra setup. Please see Location Service Guide page for more detail.

Netmera reports unhandled exceptions automatically. However, you may want not to send exception reports to Netmera. To disable reporting, you can use netmera.properties file or NetmeraProperties class as shown above. Remember, an application can have one exception tracker at a time. If you want to use another exception tracker than Netmera, you need to disable Netmera’s tracker.

You can enable/disable push inbox just by setting the property to true or false. For more detail, please see Netmera Push Notification Guide page.

You can register pop-ups directly from netmera.properties file or NetmeraProperties class as shown above. Please see Netmera Pop-up Guide page for more detail. If you set this property to true, please be sure that you have added onStart and onStop methods of NetmeraEvent to your Activities. For more detail, please see Netmera Events Guide page.

After creating netmera.properties file or NetmeraProperties instance, initialization must be done in Application class of your application. This application class must be referenced from AndroidManifest.xml file and it must extend android.app.Application class. In application tag, you need to have a name property. Its value must be the name of your Application class.

For example, you have an Application class named MyApp.java in com.netmera.myapp package. In AndroidManifest.xml file, the name attribute in application tag should be like this:

android:name=”com.netmera.myapp.MyApp”
Getting Installation Id

In order to get the installation id of the device,  you can use the following code block:

String installationId = Netmera.getInstallationID();

IO Exception with Android SDK 3.1 or higher with Netmera SDK 2.1.0 and below

For Android 3.1 or higher versions you should use background methods for network operations. Netmera’s most network operations are already done in background. However, if there is an alternative method for the same operation to do in background, you should either choose the background method directly or you should use normal method in an AsyncTask or in another thread. Because, Android does not allow performing network operations on main thread. If you get IOException, you can solve it by using background methods.

In Netmera SDK 2.2.0 and upper versions, this error is shown with a proper warning. Exception cause is given as NetworkOnMainThreadException if the exception is because of this case. Not just as IOException.

Back To Top

Netmera Push Notification

Netmera Push Notification is a service that enables developers to send push notifications and data with the notification to their applications. It is developed on the top of Google Cloud Messaging (GCM), so that it works with the Android 2.2 and later versions.

Step 1

You should get Project Number and API key from the Google and also you should enable the GCM Service. In order to complete these requirements; first open the Google APIs Console page from the link below.

https://console.developers.google.com/project

Create Project

If you haven’t created an API project yet, the page will prompt you to do so.

In Overview page of the project, you can see your project’s number. It is like Project Number: 65320729210. Take note of this value. This is your project number, and it will be used later on while registering devices.

After creation of your project, you need to enable Google Cloud Messaging for Android service. From the left menu, open your project page. Select APIs & auth -> APIs and turn the Google Cloud Messaging for Android toggle to ON and accept the terms in the Terms of Service page.

Lastly you should obtain an API key. To obtain an API key, in the main Google APIs Console page, select APIs & auth -> Credentials. You will see a screen that resembles the following:

Click Create new Key:

Create Server Key

Click Server key:

Click Create. After creation of API key, you will see a screen that resembles the following.

Take note of the API key value.

Step 2

You should save your Google API Key into the Android API Key part of application’s settings page shown in the image below.

Settings

Step 3

In order to create Android application, you must add the following configurations into the AndroidManifest.xml file.

Since our service uses Google Cloud Messaging (GCM) in background, it works with the Android 2.2 and later versions. So, if your application does not work, add the following line. In the following line, xx stands for the latest SDK version.

<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="xx"/>

Following permissions must be defined in order to use Netmera Push service.

<!-- Used to connect Netmera Services -->
<uses-permission android:name="android.permission.INTERNET" />

<!-- Push Notification requires Google Account -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />

<!-- Keeps the processor from sleeping when a message is received. -->
<uses-permission android:name="android.permission.WAKE_LOCK" />

<!-- This permission is needed to register and receive message -->
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

<!-- Create custom permission so only this app can receive its messages.
        Note that permission should be started with the package name. 
        packageName.permission.C2D_MESSAGE -->
<permission android:name="YOUR_APP_PACKAGE.permission.C2D_MESSAGE" android:protectionLevel="signature" />
<uses-permission android:name="YOUR_APP_PACKAGE.permission.C2D_MESSAGE" />

Add the following BroadcastReceiver between the application tag placed in AndroidManifest.xml file. Note that,

YOUR_APP_PACKAGE

field in the category tag must be replaced by your application’s package name.

<receiver android:name="com.netmera.mobile.NetmeraBroadcastReceiver" android:permission="com.google.android.c2dm.permission.SEND">
    <intent-filter>
        <action android:name="com.google.android.c2dm.intent.RECEIVE" />
        <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
        <category android:name="YOUR_APP_PACKAGE" /> 
    </intent-filter> 
</receiver>

You should add the following configuration for IntentService. This service is used to handle registration and sending notifications.

<service android:name="com.netmera.mobile.NetmeraIntentService" />

It is recommended to use a push notification icon that is monochromatic and flat. Default push icon is your app icon and mostly it doesn’t conform to the Android style guide. You can set your custom icon from AndroidManifest.xml file of your project. Just add the following metadata tag to your app’s AndroidManifest.xml under application tag.

<meta-data android:name="com.netmera.mobile.push_icon" android:resource="@drawable/custom_push_icon" />

where custom_push_icon is the name of a drawable resource in your package.

Step 4

Registering Device

By adding the following code in onCreate() method, you can register applications to receive notification.

If you added Google project number and push activity class to your netmera.properties file, you don’t need to call this register method without user tags and custom fields. In this case, push registration will be done by Netmera automatically.

// Firstly, you should initialize Netmera to be able to use Netmera services. See Android Guide main page for more details.

/* Register method has three parameters. 
applicationContext : current application context.
activityClass : This is the activity which should NetmeraActivity launched when user clickes on the notification. 
You can register with a class which does not extend NetmeraActivity. In such a case, you need to add event methods to your Push Activity's onCreate method. 
projectID : This is the ID that you get from the Google on the step-1.*/ 
try { 
    NetmeraPushService.register(applicationContext, projectId, activityClass); 
} catch (NetmeraException e) { 
    // Handle exception 
}

If you extend NetmeraActivity from your classes, you don’t need to add methods related with app open and app close event. These operations are done in NetmeraActivity which should be extended by your PushActivity class.

You can register with a custom Activity which does not extend NetmeraActivity. However, in this implementation, you need to apply one of the following solutions, this is for Push Notification analytics:

– Add the following code line to onCreate method of your Push Activity. However, this method is deprecated. Instead this, we recommend you to use the next solution.

//When registering without NetmeraActivity, you need to add this to onCreate() method of  your Push Activity.

NetmeraEvent.sendPushClickedEvent(getIntent());

– Add onStart and onStop methods of NetmeraEvent class to your Activity’s onStart and onStop. The activity must not be finished before onStart method of your Activity works. If you want to finish Activity after notification in onCreate method, use the first solution.

Or if you want to register different tags; you can register these tags by using NetmeraDeviceDetail objects.

NetmeraDeviceDetail deviceDetail = new NetmeraDeviceDetail(applicationContext, projectId, activityClass);
List<String> tags= new ArrayList<String>();
tags.add("News");
tags.add("Sports");
deviceDetail.setTags(tags);
try {
    NetmeraPushService.register(deviceDetail);
} catch (NetmeraException e) {
    // Handle exception
}

If device tags of NetmeraDeviceDetail object are not set; the device is only registered to BROADCAST tag.

While registering devices; by setting a NetmeraGeoLocation to the NetmeraDeviceDetail object, you can register devices to a specific location. If your device is within the specified area of your push notification, your message will be received by the application. Sending push notifications to specific areas will be explained in the sending push notification section.

NetmeraDeviceDetail deviceDetail = new NetmeraDeviceDetail(applicationContext,  projectId, activityClass);
try {
    NetmeraGeoLocation location = new NetmeraGeoLocation(41.0128, 28.9744);
    deviceDetail.setDeviceLocation(location);
    NetmeraPushService.register(deviceDetail);
} catch (NetmeraException e) {
    // Handle exception
}

You can also set custom key-value pairs over NetmeraDeviceDetail object when registering a device. Therefore, if a push notification is sent for the specific custom field(s), the devices registered to them should automatically receive the message. The developers should be aware of the fact that every time a device is registered with custom field(s), new key-value pair(s) overrides the current ones.

NetmeraDeviceDetail deviceDetail = new NetmeraDeviceDetail(applicationContext, projectId, activityClass);
Map<String, Object> customFields = new HashMap<String, Object>();
customFields.put("key1", "value1");
customFields.put("key2", "value2");
deviceDetail.setCustomFields(customFields);
try {
	NetmeraPushService.register(deviceDetail);
} catch (NetmeraException e) {
//	Handle exception
}

You can also check whether device is registered or not by using following code.

NetmeraPushService.isRegistered(applicationContext);

You can retrieve GCM registration ID of current user by using the following code.

String regId = NetmeraPushService.getRegistrationId(getApplicationContext());

If there is already registered tags and the device is again registered to different tags, these tags will be added to the previous registered tags.

deviceDetail.addTag("Tech");
try {
    NetmeraPushService.register(deviceDetail);
} catch (NetmeraException e) {
    // Handle exception
}

Now, the device is registered to Sports, News and also Tech tags.

Unregistering Device

You can unregister devices using the following code.

NetmeraPushService.unregister(applicationContext);

Or, if you want to unregister from different tags; you can unregister by using again NetmeraDeviceDetail objects.

NetmeraDeviceDetail deviceDetail = new NetmeraDeviceDetail( applicationContext );
List<String> tags= new ArrayList<String>();
tags.add("News");
tags.add("Tech");
deviceDetail.setTags(tags);
NetmeraPushService.unregister(deviceDetail);

Here; our device unregistered from News and Tech tags and remains only registered to Sports tag.

If the device is also unregistered from Sports tag; the device remains as registered to BROADCAST tag even though there is no registered tag left.

deviceDetail.addTag("Sports");
NetmeraPushService.unregister(deviceDetail);

Now, the device is only registered to Broadcast tag.

If you want to completely unregister, you must unregister without setting tags of NetmeraDeviceDetail object or use first mentioned unregister() method.

NetmeraDeviceDetail deviceDetail = new NetmeraDeviceDetail(applicationContext);
NetmeraPushService.unregister(deviceDetail);
//or 
NetmeraPushService.unregister(applicationContext);

Registered Tags of The Device: You can get the device detail and then tags of the registered device using the following code block.

NetmeraPushService.getDeviceDetailInBackground(getApplicationContext(), new NetmeraCallback() {
		@Override
		public void onSuccess(NetmeraDeviceDetail netmeraDeviceDetail) {
			List deviceTags = netmeraDeviceDetail.getTags();

		}

		@Override
		public void onFail(NetmeraException exception) {

		}
});

All Tags of All App Users: The code below is to retrieve all tags of all registered app users.You can get the all tags of all registered devices using the following code.

try {
    List<String> list=NetmeraPushService.getTags();
} catch (NetmeraException e) {
    // Handle Exception
}
Registering Push With Override Flag (Without Unregistration)

After registering a user with tags, you may want to change tags that your user is registered to. You can remove tags by unregistering from them as we explained above. Also, you can override registration tags by setting a flag on NetmeraDeviceDetail class.

We can explain function of override flag with a use case. Let’s say a user is registered to tags Sport and Cars. Something happened and you want to register this user to another tag list Flowers and Birds but removing from existing ones and you don’t want to use unregister function for some reason. So, to override tags with new ones, you need to add the following lines of code when registering. You must set override flag to true. Its default is false.

NetmeraDeviceDetail detail = new NetmeraDeviceDetail(getApplicationContext(), "sender id", YourPushActivity.class);
List<String> tags = new ArrayList<String>();
tags.add("Flowers");
tags.add("Birds");
detail.setTags(tags);
detail.setOverrideTags(true);
try {
	NetmeraPushService.register(detail);
} catch (NetmeraException e) {
	e.printStackTrace();
}

After running this code, the user will be removed from tags Sport and Cars and registered to new tags Flowers and Birds.

Adding devices to Test Group

If you want to add some of your devices to test group and use them for testing push campaigns, you should define following intent filter:

<intent-filter>
    <action android:name="android.intent.action.VIEW" />

    <category android:name="android.intent.category.DEFAULT" />
    <category android:name="android.intent.category.BROWSABLE" />
    <!-- Change yoursubdomain with your subdomain of Netmera Application Url -->
    <!-- Suppose your url is cp.netmera.com/greatapp/ -->
    <!-- Then your scheme should be nmgreatapp -->
    <data android:scheme="nmyoursubdomain" />
</intent-filter>

You should define this intent filter in one of your application activity. Suppose you have an activity namely MainActivity in your application, so this activity definition looks like this:

<activity android:name=".MainActivity" >
    <intent-filter>
        <action android:name="android.intent.action.VIEW" />

        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <!-- Change yoursubdomain with your subdomain of Netmera Application Url -->
        <!-- Suppose your url is cp.netmera.com/greatapp/ -->
        <!-- Then your scheme should be nmgreatapp -->
        <data android:scheme="nmyoursubdomain" />
    </intent-filter>
</activity>

Lastly, you should add testers from your application Settings Page.

Tester

When an e-mail address is added, an e-mail is sent to that user and if the user opens the link inside the mail from app installed mobile device, your specified activity will be opened. When this activity is opened(for example in onCreate() method), you should call NetmeraEvent.sendTestGroupEvent(this) event. Remember, if the user is not opened the application via the sent mail, the user will not be added to the test group, which means this method does nothing.

Step 5 – Deeplinking Mechanism (New Feature for navigation)

First of all, you should use Netmera Android SDK v_2.9.0 or above in order to navigate user to spesific page in the app using deeplinking mechanism after clicking a push notification. In your AndroidManifest.xml, you should add an intent filter to your Activities which you want to navigate your users after push clicks based on deeplink parameters like below:

<activity android:name=".YourActivity">
<intent-filter>
<action android:name="android.intent.action.VIEW"></action>

<category android:name="android.intent.category.DEFAULT"></category>
<category android:name="android.intent.category.BROWSABLE"></category>

<data android:scheme="yourscheme" android:host="yourhost"></data>
</intent-filter>
</activity>

For example, you can create a deeplink like below(it has two parameters: “productId” and “productCategory”). Parameters should be written in curlybraces( ex: {productCategory} )You can give them meaningful labels which could be easily understood by marketers.

Example Deeplink which is created from Netmera panel:

yourscheme://yourhost?productId={productId}&productCategory={productCategory}

If one of your activity has that scheme and host in AndroidManifest file, that Activity will be opened. You can take the query parameters which is entered from Netmera panel like below: (Note: You should define different host names for each Activity  in AndroidManifest.xml file to be sure that there is not any conflict. You can use the Activity name as host name)

String yourDeeplinkParam1= getIntent().getData().getQueryParameter("productId");
String yourDeeplinkParam2= getIntent().getData().getQueryParameter("productCategory");

Usage in Netmera Panel:

Note 1: Please be careful about the issue: ALL of your activities should call NetmeraEvent.onStart(this) in onStart methods and NetmeraEvent.onStop(this) in onStop methods. In addition, if you finish your activities (the ones which have host and scheme in manifest file) in onCreate method of that activity, you should call the code NetmeraEvent.sendPushClickedEvent(getIntent()); before you call finish() method. For more information please visit: Netmera Event Guide page.

Note 2:If you are using custom message parameters previously to navigate your users to a spesific page, don’t worry to use this feature because the system continues to send these custom parameters with push data by converting deeplink parameters to custom parameters additionally. But be sure that your custom message parameters and newly created deeplink query parameters have the same name. This could be important for your users who are not updated your application.

Step 6 – Sending Data With Push Notification(Alternative to Deeplink Mechanism)

Payload information as key-value pairs can be sent with the notification by setting values in the Message step of the ‘Push Notification’ screen. Therefore, you can deliver extra information in addition to your notification plain text.

Parameter

In your activity that you gave when you registered to push service , call the following code block to obtain key-value pairs:

Bundle extras = getIntent().getExtras();
if (extras != null) {
    if(extras.containsKey("YOUR_KEY")){
        String extra = extras.getString("YOUR_KEY");
    }
}

One more thing you must consider is that you should check whether the value exists for the given key or the key that you use is currently available in the payload information, because you can send pair information without value as well as without both key and value.

In addition, you may want to get push message text in your application. In order to get push message text in your activity that you gave when you registered to push service, you should add the following code part.

Bundle extras = getIntent().getExtras();
if (extras != null) {
    if(extras.containsKey(NetmeraIntentService.EXTRA_INCOMING_MESSAGE_TEXT)){
        String pushMessageText = extras.getString(NetmeraIntentService.EXTRA_INCOMING_MESSAGE_TEXT);
        // You can use push message text for your purpose
    }
}

Step 7 – Customized Push Notification Sound and Vibration 

You can customize push notification sounds for different push notification messages. To do this, you should add your desired notification sound files under res/raw directory. Notification sound file names must start with “nps_”. File extension for sound files must be midi or mp3.

Push Sound

While sending push notification message, you can see a combo box that contains all of your sounds, you can select one of them to play the sound with notification.

Sound List

If you want to vibrate the devices when the composed push notification is received, you should add the following permission to your AndroidManifest.xml file.

<uses-permission android:name="android.permission.VIBRATE" />

Step 8 – Handling with Rich Push Notifications

“Rich Push Notification” is a feature based on push notification, which gives the developer the choice to send the html-formatted content. Therefore, the developers can send push notifications that contains well-designed html pages to their customers instead of plain-text notifications.

After sending push notifications, you should call NetmeraPushService.handleRichPush (MyRegisteredActivity.this) method inside your push activity class. This activity class is one of the parameters of your register method and will be opened when the push notification is pressed by the user. If your push notification is a rich one; by calling handleRichPush() method, your rich push content will be loaded and shown to the user, Otherwise, you can check the return value of this method and if the returned value is false; it means this notification is a basic push and you can handle this situation as you want.

try {
    boolean isRich = NetmeraPushService.handleRichPush(MyRegisteredActivity.this);
    if(!isRich){
        // Handle basic push
    }
} catch (NetmeraException e) {
        // Handle exception
}


If you want to customize the area which a rich push is shown, you can create a webview and show rich push content in it. Calling the below code inside your push activity class is a suitable way.

 WebView webview =(WebView) findViewById(R.id.webView);

        Bundle bundle = getIntent().getExtras();
        if(bundle.containsKey(NetmeraIntentService.EXTRA_NOTIFICATION_NETMERA_ID)) {
            String pushId = bundle.getString(NetmeraIntentService.EXTRA_NOTIFICATION_NETMERA_ID);
            try{
                NetmeraPushService.handleRichPushWithId(webview,pushId);
            }catch(NetmeraException e){
                e.printStackTrace();
            }

        }

Other than the above code sample, the code below could also be used to show rich pushes. It takes NetmeraWebViewCallback as a parameter and you can detect the clicked url in the html and make custom operations based on the clicked url

try{
                NetmeraPushService.handleRichPushWithId(webview,pushId, new NetmeraWebViewCallback() {
                    @Override
                    public boolean shouldOverrideUrlLoading(WebView webView, String s) {
                        Log.i("Netmera","myurl:" + s );
                        return false;
                    }
                });
            }catch(NetmeraException e){
                e.printStackTrace();
            }

Step 9 – Push Inbox For Rich Push Notifications

“Push Inbox” is a feature, which gives the opportunity to store and redisplay rich push notifications via an interface in your application.

By default, this feature is not included in the SDK. If you want to use Netmera’s push inbox, you should add an external project named as NetmeraPushInbox to your project. You can download it from this page. If you don’t want to add this library project, you have to create an Activity to show incoming rich pushes. In this way, all coming rich push notifications are shown in your own activity which you pass as parameter when registering push. You can simply do it like this:

try {
    boolean isRich = NetmeraPushService.handleRichPush(MyRegisteredActivity.this);
    //handleRichPush(Activity) method handles push message and returns true if the incoming push is rich.
    //If the incoming push is not rich, this method returns false. In this case, you should handle standard pushes
} catch (NetmeraException e) {
        // Handle exception
}

To use Netmera’s push inbox which is in NetmeraPushInbox library project, first you download the project and add your project as shown in the figures below.

Step 1

Step 2

After importing NetmeraPushInbox library project it comes to our workspace as NetmeraPushInboxActivity shown below. NetmeraPushInboxTest is our test project to add the library.

Step 3

Step 4

Step 5

Step 6

Step 7

After that, you must add the code written below for Activity definition to your AndroidManifest.xml file.

<activity android:name="com.netmera.pushinbox.NetmeraPushInboxActivity"></activity>

In order to enable push inbox feature in your application, simply call enable method like this:

NetmeraPushService.enablePushInbox();

This enable function must be called once. After enabling, no need to call this method again.

In order to disable push inbox feature in your application, you can simply do it like this:

NetmeraPushService.disablePushInbox();

This disable function must be called once. After disabling, no need to call this method again. NetmeraPushInbox will be disabled until you call enable method.

In case you want to open Push Inbox when a custom action occurs (i.e. touch event of a button), you have to create an intent that is responsible to start NetmeraPushInboxActivity. You can simply do it like this:

Intent pushInboxIntent = new Intent(“your application context”, NetmeraPushInboxActivity.class);
startActivity(pushInboxIntent);

NetmeraPushInbox shows the list of rich push notifications that have been sent to your phone. Additionally, all controls and user interface related to push inbox are open source, so that you can change the default ones or use your custom ones if you like. You can find the related source codes under the library project.

You may not want to use Netmera’s Push Inbox. If you want to write your own push inbox code, you can use NetmeraPushInboxDataController class. There are 4 different actions that you can do.

Retrieve User Related Push Notifications

You should think push inbox as a small email inbox. There are notification messages, current user is in target users of these notifications.

To retrieve notifications for current user, you can use the following method.

NetmeraPushInboxDataController.getUserRelatedPushNotifications();

Now, you can create your own push inbox list with this list.
This method will return you a list of NetmeraRichPushObject. There are another method which retrieves notifications in background. If you run the code on the main thread, it will block the application. On Android 3.1 and upper versions, it results with an exception also. So, we recommend you to use background methods over others. Here is an example of this:

NetmeraPushInboxDataController.getUserRelatedPushNotificationsInBackground(new NetmeraCallback<List<NetmeraRichPushObject>>() {
	@Override
	public void onFail(NetmeraException e) {
		// failed
	}
	@Override
	public void onSuccess(List<NetmeraRichPushObject> list) {
		//success
	}
});

Cache mechanism can be used while retrieving user related push notifications. There are five different cache types, namely:

DEFAULT

FROM_CACHE 

FROM_NETWORK 

FIRST_CACHE_THEN_NETWORK 

FIRST_NETWORK_THEN_CACHE 

Here is an example usage of retrieving user related notifications with cache option:

NetmeraPushInboxDataController.getUserRelatedPushNotificationsInBackground(CacheType.FIRST_NETWORK_THEN_CACHE, new NetmeraCallback<List<NetmeraRichPushObject>>() {
	@Override
	public void onFail(NetmeraException exception) {
		//	failed		
	}

	@Override
	public void onSuccess(List<NetmeraRichPushObject> result) {
		//	success
	}

});
Deleting Push Notifications From Inbox

User may want to delete push notification from the inbox. To delete notifications, you can use the following method.

try {
	NetmeraPushInboxDataController.markPushAsDeleted("your push notification id to delete");
} catch (NetmeraException e) {
	//unsuccessful due to connection problems
	e.printStackTrace();
}

Parameter of the markPushAsDeleted method is var-args so that you can delete more than one notification with one request.

Marking Notifications as Read

User may want to mark push notification as read in the inbox. To mark it as read, you can use the following method.

try {
	NetmeraPushInboxDataController.markPushAsRead("notification id to mark as read");
} catch (NetmeraException e) {
	//unsuccessful due to connection problems
	e.printStackTrace();
}

Parameter of the markPushAsRead method is var-args so that you can delete more than one notification with one request.

Marking Notifications as Unread

User may want to mark push notification as unread in the inbox. To mark it as unread, you can use the following method.

try {
	NetmeraPushInboxDataController.markPushAsUnread("notification id to mark as unread");
} catch (NetmeraException e) {
	//unsuccessful due to connection problems
	e.printStackTrace();
}

Parameter of the markPushAsUnread method is var-args so that you can delete more than one notification with one request.

Interactive Push Notifications

This feature is supported by Android versions older than Android 4.1(API Level 16).

You can add interactive buttons to your push notifications and customize them to improve user engagement.

Here is step by step how to add interactive push support.

  • You need to add 2 buttons for an interactive push. These buttons must be under a set and the set must have a unique name. To be able to show the buttons with notifications, Netmera needs icons to be shown near the button. These icons must be under drawable files. You can set button icon name as in the following code sample.  For example, if you have an icon named first_button.png, you will set first_button as name. Recommended icon size is 32px*32px for xxhdpi. For others, Android will scale automatically. Remember, if Netmera cannot find any of these icons under drawable folders, notification will not be shown.

  • You need to define an action activity for button set. This activity will be started when any of the buttons is clicked. You can define your action activity same with your push activity. If user doesn’t click any of the buttons and clicks notification directly, your push activity defined when registering will be opened.

  • If you want the button to dismiss the notification and not open the app, you need to set it to true to perform in background as following. Default is false.

builder.performInBackground(true);
NetmeraPushActionButton okButton = new NetmeraPushActionButton.Builder("OK").iconName("ic_ok").performInBackground(false).build();
NetmeraPushActionButton dismissButton = new NetmeraPushActionButton.Builder("Dismiss").iconName("ic_dismiss").performInBackground(true).build();

NetmeraPushActionButtonSet buttonSet = new NetmeraPushActionButtonSet.Builder("Ok-Dismiss").actionActivity(SecondActivity.class).addButton(okButton).addButton(dismissButton).build();

NetmeraPushActionButtonSetList buttonSetList = new NetmeraPushActionButtonSetList.Builder().addNotificationActionButtonSet(buttonSet).build();
NetmeraPushService.savePushActionButtonSetInBackground(buttonSetList, null);

You can set a listener to this request if you want to be informed about the result.

You can add more than one button set to a request. Just build a new button set and add it to button set list using addNotificationActionButton(NetmeraPushActionButtonSet) method of NetmeraPushActionButtonSetList.Builder() before calling NetmeraPushService.savePushActionButtonSetInBackground(buttonSetList, null);

Now you need some small changes in AndroidManifest.xml file of your project.

Remember, we have added a BroadcastReceiver in the beginning of integration. Now, we will update it.

NetmeraBroadcastReceiver needs an action to listen action button clicks. Please add following to the receiver.

<action android:name="com.netmera.mobile.PUSH_ACTION_BUTTON_CLICKED"/>

Your receiver definition will look like this after you add the action.

<receiver android:name="com.netmera.mobile.NetmeraBroadcastReceiver" android:permission="com.google.android.c2dm.permission.SEND" >

    <intent-filter>

       <action android:name="com.google.android.c2dm.intent.RECEIVE"/>

       <action android:name="com.google.android.c2dm.intent.REGISTRATION" />

       <!——You need to add this action —>

       <action android:name="com.netmera.mobile.PUSH_ACTION_BUTTON_CLICKED"/>

       <category android:name=“YOUR_PACKAGE_NAME” />

   </intent-filter>

</receiver>

Now we are ready to go!

Here is how to send Interactive Push from Netmera control panel step by step.

  • Run the application and save your button set list.

  • Open Netmera Control Panel. Go to Campaigns page and select START AN INTERACTIVE PUSH CAMPAIGN.

  • In 3rd step of campaign creation, set your notification message and then select a Push Category. If you haven’t created one yet, click Create Category below Push Category select box.

  • In Create Category screen, name your category and assign the button set you saved from device before.

  • When you click save, Netmera will redirect you to the notification creation screen.

  • Select your push category. You will see button set tab opened. You can pass parameters to your application or you can open a web page via any of 2 buttons.

Other steps are the same with standard push notification creation.

Push and see!

1- If you send parameters with the button, you can get them using following code line in your Push Activity class:

Bundle extras = getIntent().getExtras();
if (extras != null) {
    String val = extras.getString(“your_key_from_panel”);
    //Do your work
}

2- If you use deeplink instead of message parameters, you can get deeplink parameters like below:

Example Deeplink which is created from Netmera panel:

yourscheme://yourhost?productId={productId}&productCategory={productCategory}

If one of your activity has that scheme and host in AndroidManifest file, that Activity will be opened. You can take the query parameters which is entered from Netmera panel like below: (Note: You should define different host names for each Activity in AndroidManifest.xml file to be sure that there is not any conflict. You can use the Activity name as host name)

String yourDeeplinkParam1= getIntent().getData().getQueryParameter("productId");
String yourDeeplinkParam2= getIntent().getData().getQueryParameter("productCategory");
Sending Image With Notification To Notification Bar

This feature is supported by Android versions older than Android 4.1(API Level 16).

You can send image url to be shown in the status bar with your incoming push notifications. You just need to set an image url while sending your notification. In the 3rd step of notification creation screen, add an image url to Large Icon field.

Other steps are the same with standard notification.

Remember, if your Android version is lower than Android 4.1(API Level 16), you will see a standard notification instead notification with picture.

Recommended image size is 1024px width and 512px height for xxhdpi devices. For others, Android will scale automatically.

Back To Top

Netmera Event

NetmeraEvent class provides a simple to use interface for tracking users’ behaviors during application usage.

Netmera SDK tracks following events internally:

App Installation Events

This event will be sent automatically when your app installed on a device. It is used to track number of your users.

Activity Start (App Open) Events

Activity Start (App Open) events allow you to track your application being launched. By adding the following line to the onStart() method of all of your activity classes, you’ll begin to collect data when and how often your application is opened, how many time do your users spend in the app.

If you add activity start event, please add activity stop event also.

NetmeraEvent.onStart(this);
Activity Stop (App Close) Events

Activity Stop (App Close) events allow you to track your application closed. By adding the following line to the onStop() method of all of your activity classes, you’ll begin to collect data when and how often your application is closed. If you add activity stop event, please add activity start event also.

NetmeraEvent.onStop(this);

***Activity start and activity stop events should be added all of the activities except push activity in an app if push activity extends NetmeraActivity. If it does not extend, you must add onStart and onStop events to the push activity class.

 Time In App Events

This event type is for tracking time in application data. When you call the app close event, this event will be sent automatically if you add open and close events.

 Push Notification Clicked Events
  • If your push activity extends NetmeraActivity, this event will automatically be sent. You don’t need to do anything.

  • If not, in your push activity, you need to add onStart() and onStop() methods.

  • If you want to finish your Activity in onCreate or before onStart or if you use your custom activity which does not extend NetmeraActivity, you need to call following before finishing your Activity. You must add the following to onCreate() method of your Push Activity.

NetmeraEvent.sendPushClickedEvent(getIntent());

It will be checked if user clicked push and show if there is any incoming push. If there is no push message incoming, the method does nothing.

If your push activity does not extend NetmeraActivity, you need to add Activity Start and Activity Stop events explained above.

User Location Changed Events

This event will be sent automatically to Netmera with user location info if your app has ACCESS_COARSE_LOCATION permission. It uses coarse location. Otherwise, these event data can’t be collected.

App Exception Events

This event will be sent if there is any exception thrown by your app and if it is unhandled. Unhandled exception data will be sent automatically to Netmera. If you want, you can send your handled exceptions to Netmera. Click here to learn how.

Custom Events

Netmera allows you to create custom events and track different behaviors of users. By adding the following line of code to your app code, you can send your own events. When you want to create new segments or send event related pop-ups, you can use these events. Your event name will appear on the segment list when you want to create a new one.

String eventName = "Your custom event name";
try {
    NetmeraEvent.sendCustomEvent(eventName);
} catch (NetmeraException e) {
    // Handle exception
}
Custom Events With Key – Single Value

Netmera allows you to send data with your custom event. The data can be used while creating segments and triggered push notification to target deeply.

String eventName = "Your custom event name";
JSONObject data = null;
try {
    data = new JSONObject();
    data.put("event data key 1", "event data 1");
    data.put("event data key 2", "event data 2");
} catch(JSONException e) {
    // Handle exception
}
try {
    NetmeraEvent.sendCustomEventWithData(eventName, data);
} catch (NetmeraException e) {
    // Handle exception
}
Custom Events With Key-Multiple Values

Similar to previous example, you can also put JSONArray as a value. This could be used for the cases which a key requires multiple values. While you are creating a segment from Netmera Panel, this values could be selected one by one. (example: selecting just “News” as a value).

String eventName = "Your custom event name";
JSONObject data = null;
JSONArray multipleValues = null;

try {
    data = new JSONObject();
    multipleValues = new JSONArray();
    multipleValues.put("News");
    multipleValues.put("Sports");
    data.put("category", multipleValues);   // multiple values
    } catch(JSONException e) {
            // Handle exception
    }
    try {
        NetmeraEvent.sendCustomEventWithData(eventName, data);
    } catch (NetmeraException e) {
            // Handle exception
    }

Back To Top

Netmera Pop-up

Pop-ups are very helpful in increasing in-app communication. They are shown according to user actions such as app opens, specific page views, or other valuable custom actions that you have decided. Best thing about Netmera pop-up service is that you do not need to change anything in your app to change the message that is displayed. Each time the user opens the app; Netmera SDK will download the latest pop-up rules and display the current message.

Registration and Initialization

To be able to use Netmera Pop-up, you should enable pop-up retrieval on start-up using netmera.properties file or NetmeraProperties class. See Initialization for more.

Netmera will retrieve pop-ups automatically.

Pop-up will be triggered by events. For example, if user opens the app and if there is any pop-up triggered by open app event, you can show it to user. Netmera will not show pop ups automatically after these events.

Netmera will index pop-ups to show when and where ever you want.

Checking Pop-ups

In your each view opened, you need to set a PopupStateListener. This listener has two methods. One is named as onReady() and it is to be informed after the pop-up list is ready to use. Other method is onEvent(List<NetmeraPopup>) and it is called after an event sent to Netmera and if there is a pop-up triggered by this event.

You can use the listener as shown below.

NetmeraPopupService.setPopupStateListener(new PopupStateListener() {
    @Override
    public void onReady() {
        //Pop-up list retrieved from Netmera successfully
    }

    @Override
    public void onEvent(List<NetmeraPopup> popups, String eventType) {
	try {
            //Handle your pop-ups here
            popups.get(0).show(yourWebView); 
        } catch (Exception e) { 
            e.printStackTrace(); 
        } 
    } 
});

You can check if there is any pop up to show by calling the code below.

boolean appHasPopup = NetmeraPopupService.appHasPopupToShow();

If you want to check pop ups for a specific event, call this method.

boolean appHasPopup = NetmeraPopupService.appHasPopupToShow(String);

String parameter in the method is event name. You may want to check pop-ups for your custom events or Netmera default events. For Netmera event type names, use variables defined on EventType class. There is 1 event which is sent automatically by Netmera for now. Namely;


APP_OPENED: When application is opened and you called NetmeraEvent.onStart(Activity) method from onStart() methods of your activities.

Getting Deserved Pop-ups

If you want to get events in a method other than onEvent of the listener, you need some more code.

If there is any pop-up to show (user sent some event and deserved to see any pop-up) and you want to show it, get pop-up list by using the following method.

List<NetmeraPopup> popupList = NetmeraPopupService.getAllPopupsToShow();

This method will return all deserved pop ups. However, you may want to get pop ups which are related with some events. In a situation like this, you should use the following method. You can use variable defined on EventType class for the parameter event name or your custom event name.

List<NetmeraPopup> popupList = NetmeraPopupService.getEventRelatedPopupsToShow(String);
Showing a Pop-up

From the list, you should choose which pop up you want to show. You can define more than one pop up for each event and that is why these methods return list instead of one unique NetmeraPopup object.

After selecting a pop-up, you should call one of show(); methods on NetmeraPopup class.

There are 2 methods to show pop ups. One of them takes Activity as parameter. Netmera will add pop up to this activity and show it. You should call this method from the same activity which is given as parameter activity to the method. Usage of the method may be like this:

popup.show(this);

The other show(); method takes WebView as parameter. You can give Netmera a WebView. Current pop-up will be shown in this WebView.

popup.show(webview);

Back To Top

Netmera Location Service

NetmeraLocationService (previously NetmeraGeofenceService) is a service that enables developers tracking location for NetmeraPush service. If you want to send locational push notifications and if you use this service, you don’t need to track device locations anymore. This service automatically updates device location. It allows you to create location based push notification campaigns with time and distance intervals. When your users get closer to specific location, you can send automated push messages to them in certain time interval.

Using the following steps, you can easily add Location Tracking feature to your apps.

Step 1 Location Service uses Google Play Services SDK. You need to add Google Play Services library project to your project. Here is the link about how to set up development environment and project with Google Play Services SDK. http://developer.android.com/google/play-services/setup.html

After installation and creating a project with Google Play Services SDK, you need to add location permissions to your Manifest.xml file. There are 2 different types of permission for this. First one is ACCESS_COARSE_LOCATION. This permission gets coarse location. It allows you to access approximate location derived from network location sources such as cell towers and Wi-Fi. The other is ACCESS_FINE_LOCATION. It allows your app to access precise location from location sources such as GPS, cell towers, and Wi-Fi. If you don’t need exact location of user and if your app is not a map/navigation app, we advise you to use coarse location over fine. For battery life optimization, coarse is also better than fine since it does not use GPS.

To start Netmera Location Service, you need to add the following line to your Manifest.xml file.

<service android:name="com.netmera.mobile.LocationService" />

When you run the project, this service will automatically start collecting location data and send it to Netmera if you enabled location tracking in netmera.properties file or NetmeraProperties Object’s builder which could be used in Netmera.init function. Otherwise, you need to set your default values and call necessary methods mentioned below. Default parameters are as follows:

Interval distance: 150 meters

Interval time: 15 minutes

Fastest interval: 10 minutes

Priority: PRIORITY_LOW_POWER

These are optimized values for location service. If you want to customize values, you need to create your own NetmeraLocationSettings object and start Location Service with this NetmeraLocationSettings object.

Step 2

Before starting NetmeraLocationService, you should create a NetmeraLocationSettings object. You can change its default parameters as you wish. If you don’t set optional values, default values will be used.

Let’s clarify the terms that we will use them to customize Location Service.

The fastest interval parameter sets the fastest interval for location updates, in milliseconds. Please read the documentation for details on Google Play Services Reference document. Click here to open it.

The interval distance parameter (intervalMeters) can be used to control the frequency of location updates. If it is greater than 0, then the location provider will send an update when the location has changed by at least interval distance meters, OR at least the interval time (intervalSeconds) seconds have passed. Location Service will read the location and send location updates to Netmera to check if there is any event/trigger/geofence push related to this location. For more detail about this interval time parameter, please click here. For interval distance parameter, click here.

The other important parameter is priority.

There are 4 types of priority. PRIORITY_BALANCED_POWER_ACCURACY, PRIORITY_HIGH_ACCURACY, PRIORITY_LOW_POWER, PRIORITY_NO_POWER. Please follow the link to get more information about them. Click here.

An example usage of the NetmeraLocationSettings class may be like this.

NetmeraLocationSettings locationSettings = new NetmeraLocationSettings();
locationSettings.setIntervalSeconds(15 * 60).setIntervalMeters(200)
.setFastestInterval(10 * 60 * 1000).setPriority(NetmeraLocationSettings.PRIORITY_LOW_POWER);
NetmeraLocationService.init(locationSettings, getApplicationContext());
NetmeraLocationService.startLocationService();

*In this example setIntervalSeconds parameter equals to 15 minutes, intervalMeters parameter is equal to 200 meters and setFastestInterval parameter(in miliseconds) is equal to 10 minutes. You can change values based on your requirements. It is just an example. If you need more frequent location updates, you can change these values but please keep in mind that using so small intervals will decrease phone’s battery level more.

After creating NetmeraLocationSettings object, you should initialize NetmeraLocationService by passing NetmeraLocationSettings object and context. To start NetmeraLocationService you should call startLocationService() method.

NetmeraLocationService.init(locationSettings, getApplicationContext());
NetmeraLocationService.startLocationService();

If you want to stop NetmeraLocationService, you should call stopLocationService() method on NetmeraLocationService class. After calling this method, Netmera will not receive location updates anymore.

NetmeraLocationService.stopLocationService();

Back To Top

Netmera Exception Reporter

Netmera has an exception reporting mechanism inside the SDK. With the help of this special feature, you will be able to track exceptions in your application and see the details in exception browser of Netmera website. However, Netmera iOS SDK has disabled the exception reporter mechanism and has not tracked any exception by default. To enable it, you should first add PLCrashReporter framework into your project (For more detail about PLCrashReporter, click here). Then you should make sure that you set YES for ExceptionReportingEnabled flag in NetmeraSettings.plist. After all these are done, you can benefit exception reporting mechanism at full power.

For unhandled exceptions and application crashes are catched automatically by SDK, and they will be reported to Netmera immediately when your application is launched at the first time after crashes. However, you should add a line of code to be able to see the handled exceptions reports if you want to tracked them. In a try-catch block, if there is any exception occurred in the try block, you should add the following line of code to your catch block to send the report about the exception to Netmera.

@try {
// Your try block that may cause the application to send exceptions.
}
@catch (NSException *exception) {
    [NMExceptionReporter sendExceptionReport:exception];
}

Back To Top

Android API

Rest API

Rest API

By using REST API you can interact with Netmera just sending HTTP request. You can implement your own SDK’s by using our REST API.

All REST requests are sent via https://api.netmera.com domain. For authentication you should add X-netmera-api-key into the HTTP Header. You can get your API_KEY from the overview page. You should also set the Content-Type as application/json on the request header.

You can easily register-unregister devices, send notifications, get notification and device info by using REST API. The following code is used to send notification. It has the title and notificationMsg as a required parameter.


Note: Please be aware of that “richPushHtml” (If your request includes this attribute, your push is counted as Rich push) and “largeIconUrl” (Big Picture Style Push-Push with Image- in Android devices 4.1+) and “customJson” (message parameters) attributes are optional.

curl -X POST \
-H "X-netmera-api-key: ${API_KEY}" \
-H "Content-Type: application/json" \
-d '{
        "target" : {
                "platforms": ["ANDROID", "IOS", "WP"],
                "tags": ["tag1", "tag2"],
                "customFields": {
                        "key1": "value1",
                        "key2": "value2"
                }
        },
        "notification" : {
	        "title": "My First Push Notification",
        	"notificationMsg": "My First Push Notification message",
        	"richPushHtml": "<html> Example Rich Push Content </html>",
		"largeIconUrl": "${YOUR_IMAGE_URL}", 
        	"customJson": {
                        "key1": "value1",
                        "key2": "value2"
        	}
        }
}' \
https://api.netmera.com/push/1.2/notification
curl -X POST  \
-H "X-netmera-api-key: ${API_KEY}" \
-H "Content-Type: application/json" \
-d '{
        "title": "My First Push Notification",
        "notificationMsg": "My First Push Notification message", 
        "richPushHtml": "<html> Example Rich Push Content </html>" 
}' \
https://api.netmera.com/push/1.1/notification
ERROR CODES

You can reach  the error codes and their meanings from this page.

Back To Top

Push API

Push API allows you to manage device registration and notifications. By sending HTTP request you can register/unregister devices, you can find the number of registered devices and you can delete devices using platform and tag informations. You can also send notification and get the details of sent notification via REST API.

PARAMETERS

X-netmera-api-key :  Netmera API Key. You can get it from the application’s overview page on netmera.com

registrationId :  This is equivalent to the regId in Android and deviceToken in the IOS platform.

platform :  The name of the platform could be “ANDROID”, “IOS” or “WP”.

tags : List of the unique tags to which the device is registered.

latestLocation : Latest location of the registered device. It is an array which has two parameters which are latitude and longitude respectively.

iid : Unique installation id of the device that is generated by Netmera SDK.

timeZone :  Current time zone of the device.

max : Maximum number of the contents returned as the result. Default value is 10.

page : It is used to retrieve the contents of a given page. Default value is 0. If you set page as 1, then it will skip page*max and retrieve the next max items.

title : This is the title of the notification.

notificationMsg : This is the message of the notification you want to send.

richPushHtml : If you want to send rich push notification, then you can add html into this parameter.

customJson : Custom json data which holds key-value pairs and used to send different data as a payload to the push notification. You can send custom data and use its values in the application.

customFields : It is a key-value pairs which is used to add those fields during push user registration. It is also used to filter users during sending push notification.

overrideTags : This is a boolean field whose default value is FALSE. If it is setted as TRUE then new tag list will override the current tag list of the push user.Otherwise it will merge two lists.

showInPushInbox : This is a boolean field to determine to show push notification in push inbox.

Register Device

Following code can be used to register device to get push notification. registrationId and platform are the required fields. You can get registrationId from Apple for IOS devices which is called deviceToken and Google for Android which is equivalent to the regId. platform field could be “ANDROID”, “IOS” or “WP”. You can also set latest location, installation id and time zone of the device while registering. You can group devices by registering them into different tags using the tags field and send notification using the specific tag. You can also add customFields during registration and filter the users with the given custom field(s) during sending notification. There is an optional field namely overrideTags which is used to override older tag list with the new one.

curl -X POST \
-H "X-netmera-api-key: ${API_KEY}" \
-H "Content-Type: application/json" \
-d '{
        "registrationId": "${REGISTRATION_ID}",
        "platform": "ANDROID",
        "tags": ["tag1", "tag2"],
        "latestLocation": [latitude, longitude],
        "iid": "${INSTALLATION_ID}",
        "timeZoneHourOffset":"0",
        "customFields": {
            "key1": "value1",
            "key2": "value2"
        },
        "overrideTags" : true
}' \
https://api.netmera.com/push/1.1/registration

If registration is successful, you will get the code 1000 and message OK as a response.

{ "message" : "OK", "code" : 1000 }

In case of exception occurs while registration, following response message will be sent. For example if registrationID is null or empty then you will get following response.

{ "message" : "Registration ID cannot be null nor empty", "code" : 2003 }

Batch Register Device

Following code can be used to register multiple devices at the same time. Instead of registering single device, you can post array of devices for bulk registration. This method will help you to import your devices into Netmera easily.

curl -X POST \
-H "X-netmera-api-key: ${API_KEY}" \
-H "Content-Type: application/json" \
-d '{
        "registrations": [
	{
	    "registrationId": "${REGISTRATION_ID}",
	    "platform": "ANDROID",
	    "tags": ["tag11", "tag12"],
	    "latestLocation": [latitude, longitude],
	    "iid": "${INSTALLATION_ID}",
	    "timeZoneHourOffset":"0",
	    "customFields": {
	        "key11": "value11",
	        "key12": "value12"
	    },
	    "overrideTags" : true
	},
	{
	    "registrationId": "${REGISTRATION_ID}",
	    "platform": "IOS",
	    "tags": ["tag21", "tag22"],
	    "latestLocation": [latitude, longitude],
	    "iid": "${INSTALLATION_ID}",
	    "timeZoneHourOffset":"1",
	    "customFields": {
	        "key21": "value21",
	        "key22": "value22"
	    },
	    "overrideTags" : false
	},
	{
	    "registrationId": "${REGISTRATION_ID}",
	    "platform": "WP",
	    "tags": ["tag31", "tag32"],
	    "latestLocation": [latitude, longitude],
	    "iid": "${INSTALLATION_ID}",
	    "timeZoneHourOffset":"2",
	    "customFields": {
	        "key31": "value31",
	        "key32": "value32"
	    },
	    "overrideTags" : true
	}]
}' \
https://api.netmera.com/push/1.1/registration/batch

Send Notification

The following code is used to send notification. It has the title and notificationMsg as required parameters. You can also set the platforms, tags and custom fields to filter the devices. If you do not set those parameters then it will broadcast notification to the all available devices.

curl -X POST \
-H "X-netmera-api-key: ${API_KEY}" \
-H "Content-Type: application/json" \
-d '{
        "target" : {
                "platforms": ["ANDROID", "IOS", "WP"],
                "tags": ["tag1", "tag2"],
                "customFields": {
                        "key1": "value1",
                        "key2": "value2"
                }
        },
        "notification" : {
	        "title": "My First Push Notification",
        	"notificationMsg": "My First Push Notification message",
        	"richPushHtml": "<html></html>",
        	"showInPushInbox" : false,
        	"customJson": {
                        "key1": "value1",
                        "key2": "value2"
        	}
        }
}' \
https://api.netmera.com/push/1.2/notification

Send Notification to a Specific Device

You can also send the notification only to a device by specifying the registrationId. If you send notification by using registration Id, there is no need to add platform and tags parameters, they will be discarded.

curl -X POST \
-H "X-netmera-api-key: ${API_KEY}" \
-H "Content-Type: application/json" \
-d '{
        "target" : {
                "registrationId": "${REGISTRATION_ID}",
        },
        "notification" : {
	        "title": "My First Push Notification",
        	"notificationMsg": "My First Push Notification message",
        	"richPushHtml": "<html></html>",
                "customJson": {
                    "key1": "value1",
                    "key2": "value2"
                }
        }
}' \
https://api.netmera.com/push/1.2/notification

Send Notification to Segment

You can also send the notification only to a segment by specifying the name of the segment.

curl -X POST \
-H "X-netmera-api-key: ${API_KEY}" \
-H "Content-Type: application/json" \
-d '{
        "target" : {
                "platforms": ["ANDROID", "IOS", "WP"],
		 "segments" : ["yourSegmentName"]
        },
        "notification" : {
	        "title": "New Notification",
        	"notificationMsg": "Click here to go app"
        }
}' \
https://api.netmera.com/push/1.2/notification

If notification is sent successfully, you will get the code 1000 and message OK as a response. Sent notification ID will be shown as a response inside the result block.

{
    "message" : "Push notification is sending",
    "code" : 1000,
    "result" : { "notificationId" : "5199eb7244ae79c2d5c59ed7" }
}

In case of exception occurs while sending notification, following response message will be sent. For example, when notification is sent without setting notificationMsg field, you will get the following exception message as a response.

{ "message" : "notificationMsg cannot be null nor empty", "code":2003 }

Send Notification to Location

You can also send the notification that matches with the given location. You can also set other parameters such as tags, custom fields to filter users with location. It will find users that matches with all given parameters. You can filter users by location in two ways. You can either send CIRCLE or BOX push.

Circle Push

CIRCLE push takes one location (lat1, lng1) and a distance as a parameter and by taking given location as a base finds the users located in the given distance far away. Unit of the distance field is KM.

curl -X POST \
-H "X-netmera-api-key: ${API_KEY}" \
-H "Content-Type: application/json" \
-d '{
        "target" : {
            "platforms": ["ANDROID", "IOS", "WP"],
            "tags": ["tag1", "tag2"],
            "customFields": {
                "key1": "value1",
                "key2": "value2"
        	},
    	    "pushLocation": {
     	        "lat1": "41.0",
     	        "lng1": "28.0",
     	        "distance" : 100,
    	        "locationType": "CIRCLE"
   	    }
        },
        "notification" : {
	        "title": "My First Push Notification",
        	"notificationMsg": "My First Push Notification message",
        	"richPushHtml": "<html></html>",
                "customJson": {
                    "key1": "value1",
                    "key2": "value2"
        	}
        }
}' \
https://api.netmera.com/push/1.2/notification

Box Push

BOX push takes two locations (lat1, lng1, lat2, lng2) as a parameter and by creating box it finds the users located inside the given box.

curl -X POST \
-H "X-netmera-api-key: ${API_KEY}" \
-H "Content-Type: application/json" \
-d '{
        "target" : {
	"platforms": ["ANDROID", "IOS", "WP"],
	"tags": ["tag1", "tag2"],
	"customFields": {
                "key1": "value1",
                "key2": "value2"
        	},
    	"pushLocation": {
     	    "lat1": "41.0",
     	    "lng1": "28.0",
     	    "lat2": "42.0",
     	    "lng2": "29.0",
    	    "locationType": "BOX"
   	}
        },
        "notification" : {
	        "title": "My First Push Notification",
        	"notificationMsg": "My First Push Notification message",
        	"richPushHtml": "<html></html>",
	        "customJson": {
                    "key1": "value1",
                    "key2": "value2"
        	}
        }
}' \
https://api.netmera.com/push/1.2/notification

Get Notification

Following code gets the details of notification by using its ID.

curl -X GET  \
-H "X-netmera-api-key: ${API_KEY}" \
-H "Content-Type: application/json" \
https://api.netmera.com/push/1.1/notification/{ID}

If notification is get successfully, you will get the code 1000 and message OK as a response. You will get the details of notification inside the result block as shown below.

{
    "message": "OK",
    "result": {
        "notification": {
            "tags": [],
            "message": "Rest Api Push Notification -673537462",
            "customJson": [],
            "notificationId": "519cb40044aefae1c8af1482",
            "title": "Rest Api Push Notification -673537462",
            "results": {
                "ANDROID": {
                    "sendDate": "2013-05-22T15:03:12.025Z",
                    "error": null,
                    "pushStatus": "FINISHED",
                    "finishDate": "2013-05-22T15:06:11.378Z",
                    "successCount": 125000,
                    "failedCount": 1200
                },
                "IOS": {
                    "sendDate": "2013-05-22T15:03:12.025Z",
                    "error": null,
                    "pushStatus": "FINISHED",
                    "finishDate": "2013-05-22T15:06:37.378Z",
                    "successCount": 236000,
                    "failedCount": 2700
                },
                "WP": {
                    "sendDate": "2013-05-22T15:03:12.025Z",
                    "error": null,
                    "pushStatus": "FINISHED",
                    "finishDate": "2013-05-22T15:05:26.378Z",
                    "successCount": 58000,
                    "failedCount": 3200
                }
            },
            "pushStatus": "FINISHED",
            "pushType": "STANDARD",
            "platforms": [
                "ANDROID",
                "IOS",
                "WP"
            ],
            "richPushHtml": null
        }
    },
    "code": 1000
}

pushType can be one of these values: “STANDART”, “RICH”

pushStatus can be one of these values: “DRAFT”, “SENDING”, “FINISHED”, “FAILED”

In case of exception occurs while sending notification, following response message will be sent. For example, when given notificationID is wrong or invalid and requested notification will not found then following error message will be shown.

{ "message" : "Notification with this notificationId does not exist!", "code":2108 }

Get Device Info by ID

You can get the registered device info by running the following code. It gets a registrationId as a parameter. You can get the latest location, tag(s), installation ID and time zone of the device as a response.

curl -X GET  \
-H "X-netmera-api-key: ${API_KEY}" \
-H "Content-Type: application/json" \
https://api.netmera.com/push/1.1/registration/${REGISTRATION_ID}

If device info is get successfully, you will get the code 1000 and message OK as a response. Device info is shown inside the result block.

{
    "message" : "OK",
    "code" : 1000,
    "result" : {
        "registration" : {
             "tags" : ["tag1","tag2"],
             "platform" : "ANDROID",
             "latestLocation" : {"latitude": 41.0, "longitude": 29.0, "timeZone": 0 },
             "iid" : "e35b3f3d-8e09-4442-aff8-7fc16a0b03f0",
             "udid" : "a88fqsdg8as87rgq87wrg8as8dg78zDf8a98sdf98asd8fa7sdf"	
         }
    }
}

In case of exception occurs while getting device info, following response message will be sent. For example, when the requested deviceID is not registered on our system then following error message will be shown.

{ "message":"The device is not registered", "code":2102 }

Get Device Info by Query

You can get the registered devices’ info which fit the given query by running the following code. You can get the latest location, tag(s), installation ID and time zone of the devices as a response.

curl -X GET  \
-H "X-netmera-api-key: ${API_KEY}" \
-H "Content-Type: application/json" \
-G \
--data-urlencode 'tags = ["tag1", "tag2"]' \
--data-urlencode 'platforms = ["ANDROID", "IOS", "WP"]' \
--data-urlencode 'customFields = {"key1":"value1", "key2":"value2"}' \
--data-urlencode 'max = 10' \
--data-urlencode 'page = 0' \
https://api.netmera.com/push/1.2/registration

If device info is get successfully, you will get the code 1000 and message OK as a response.

{
    "message" : "OK",
    "code" : 1000,
    "result" : {
	"registration" : [{
            "tags" : ["tag1","tag2"],
            "platform" : "ANDROID",
            "customFields": {"key1": "value1", "key2": "value2"},
            "latestLocation" : {"latitude": 41.0, "longitude": 29.0, "timeZone": 0 },
            "registered": true,
            "iid" : "e35b3f3d-8e09-4442-aff8-7fc16a0b03f0",
            "udid" : "a88fqsdg8as87rgq87wrg8as8dg78zDf8a98sdf98asd8fa7sdf"	
        }, {
            "tags" : ["tag3","tag4"],
            "platform" : "IOS",
            "customFields": {"key1": "value1", "key2": "value2"},
            "latestLocation" : {"latitude": 41.0, "longitude": 29.0, "timeZone": 0 },
            "registered": false,
            "iid" : "e35b3f3d-8e09-4442-aff8-7fc16a0b03f1",
            "udid" : "a88fqsdg8as87rgq87wrg8as8dg78zDf8a98sdf98asd8fa7sde"	
        }]
    }
}

In case of exception occurs while getting device info, following response message will be sent.For example, when the requested deviceID is not registered on our system then following error message will be shown.

{ "message":"The device is not registered", "code":2102 }

Get Registration Count

This method is used to find the counts of the registered devices. If you don’t set tags and platforms parameters it will find the counts of the all devices. Otherwise it will find the devices that registered to given tag(s) or given platform(s).

curl -X GET  \
-H "X-netmera-api-key: ${API_KEY}" \
-H "Content-Type: application/json" \
-G \
--data-urlencode 'tags = ["tag1", "tag2"]' \
--data-urlencode 'platforms = ["ANDROID", "IOS", "WP"]' \
https://api.netmera.com/push/1.1/registration/count

If device count is get successfully, you will get the code 1000 and message OK as a response. You will get the device count inside the result block as shown below.

{
    "message" : "OK",
    "code" : 1000
    "result" : { "count" : 4 }
}

In case of exception occurs while getting device info, following response message will be sent. For example, if sended platform names will be invalid then you will get following error message.

{ "message" : "Error occurred while retrieving tags from json array. It is invalid or corrupted", "code" : 2009 }

Unregister Device by ID

The following code unregisters the device by using registrationId. If you do not want to send push notification to any users, you can unregister them from the device list.

curl -X DELETE  \
-H "X-netmera-api-key: ${API_KEY}" \
-H "Content-Type: application/json" \
https://api.netmera.com/push/1.1/registration/${REGISTRATION_ID}

If device is unregistered successfully, you will get the code 1000 and message OK as a response.

{ "message" : "OK", "code" : 1000 }

In case of exception occurs while unregistering device, following response message will be sent. For example if API Key is invalid then you will get following response.

{ "message" : "API key cannot be null or empty", "code" : 2003 }

Unregister Device by ID & Tag

Following code unregisters the device from the given tag(s). You can still send notification to the remaining tag(s) of the device or you can send broadcast notification if user has no tag.

curl -X DELETE \
-H "X-netmera-api-key: ${API_KEY}" \
-H "Content-Type: application/json" \
-G \
--data-urlencode 'tags = ["tag1", "tag2"]' \
https://api.netmera.com/push/1.1/registration/${REGISTRATION_ID}

If device is unregistered successfully from the given tag(s), you will get the code 1000 and message OK as a response.

{ "message" : "OK", "code" : 1000 }

In case of exception occurs while unregistering device, following response message will be sent.For example if tags data is invalid then you will get following response.

{ "message" : "Error occurred while retrieving json object. It is invalid or corrupted", "code" : 2009 }

Back To Top

Event API

By using our Event API you can create custom events and store event data on our servers. You can use custom events to send push notifications. For example, you can create FacebookShareEvent and send notification when user clicks facebook share button.

PARAMETERS:

X-netmera-api-key :  Netmera API Key. You can get it from the application’s overview page on netmera.com

et : Name of the fired event.

iid : Unique installation id of the device that is generated by Netmera SDK.

data : Custom data that is sent with fired event.

cf : Custom fields that will be used to matched with the custom fields saved during push registration.

Fire Event

To fire an event with custom attributes add required parameters (et and iid) and post it to the following URL. You can add key-value pairs into the data json.

curl -X POST \
-H "X-netmera-api-key: ${API_KEY}" \
-H "Content-Type: application/json" \
-d '{
"et": "${CUSTOM_EVENT_NAME}",
	"iid": "${INSTALLATION_ID}",
	"data": {"key1":"value1","key2":"value2"}
}' \
https://api.netmera.com/event/1.0/fireEvent

If the event is fired successfully, you will get the code 1000 and message OK as a response.

{ "message" : "OK", "code" : 1000 }

In case of exception occurs while creating event, following response message will be sent. For example if API Key is invalid then you will get following response.

{ "message" : "API key is null or empty!", "code" : 2010 }
Bulk Fire Event

By using the following code you can create several events in one request. Data format of the events is same as in the fireEvent.

curl -X POST \
-H "X-netmera-api-key: ${API_KEY}" \
-H "Content-Type: application/json" \
-d '[
    {
        "et": "${CUSTOM_EVENT_NAME}",
        "iid": "${INSTALLATION_ID}",
        "data": {
        "key1":"value1",
        "key2":"value2"
        }
    },
    {
        "et": "${CUSTOM_EVENT_NAME}",
        "iid": "${INSTALLATION_ID}",
        "data": {
        "key1":"value1",
        "key2":"value2"
        }
    }
]' \
https://api.netmera.com/event/1.0/fireEvent/bulk
Fire Event With Custom Fields

If you do not know or can’t access the installation id of a device, you can find users by using the custom fields as shown below and fire event. With this method, you can also fire events for multiple users that matched with the custom query.

curl -X POST \
-H "X-netmera-api-key: ${API_KEY}" \
-H "Content-Type: application/json" \
-d '{
    "et": "${CUSTOM_EVENT_NAME}",
    "cf": {
        "key1":"value1",
        "key2":"value2"
    },
    "data": {
        "key1":"value1",
        "key2":"value2"
}
}' \
https://api.netmera.com/event/1.0/fireEvent
Bulk Fire Event By Custom Fields

By using the following code you can create several events in one request. Data format of the events is same as in the fireEvent by custom fields.

curl -X POST \
-H "X-netmera-api-key: ${API_KEY}" \
-H "Content-Type: application/json" \
-d '[
    {
        "et": "${CUSTOM_EVENT_NAME}",
        "cf": {
               "key1":"value1",
                    "key2":"value2"
        },
        "data": {
        "key1":"value1",
        "key2":"value2"
        }
    },
    {
        "et": "${CUSTOM_EVENT_NAME}",
        "cf": {
               "key1":"value1",
                    "key2":"value2"
        },
        "data": {
        "key1":"value1",
        "key2":"value2"
        }
    }
]' \
https://api.netmera.com/event/1.0/fireEvent/bulk

Back To Top

Tag API

PARAMETERS

X-netmera-api-key :  Netmera API Key. You can get it from the application’s overview page on netmera.com

customFields : It is a key-value pairs which is is used to add those fields during push user registration.

List Tags

Following code is used to list all existing tags for the given application apikey.

curl -X GET \
-H "X-netmera-api-key: ${API_KEY}" \
-H "Content-Type: application/json"
https://api.netmera.com/tag/1.0
Create a Tag

Following code is used to create a tag, Note that, tags are created implicitly when devices registered with tag information.

curl -X POST \
-H "X-netmera-api-key: ${API_KEY}" \
-H "Content-Type: application/json"
https://api.netmera.com/tag/1.0/{tagName}
Delete a Tag

Following code is used to delete a tag, Note that, this will delete the tag from all devices, all devices registered with this tag will be unregistered from the given tag.

curl -X DELETE \
-H "X-netmera-api-key: ${API_KEY}" \
-H "Content-Type: application/json"
https://api.netmera.com/tag/1.0/{tagName}
Get a Tag Detail

Following code is used to get detailed information related with the tag.

curl -X GET \
-H "X-netmera-api-key: ${API_KEY}" \
-H "Content-Type: application/json"
https://api.netmera.com/tag/1.0/{tagName}
Adding Devices to Tag

Following code is used to add multiple devices to the tag. All devices will be registered to the given tag.

curl -X POST \
-H "X-netmera-api-key: ${API_KEY}" \
-H "Content-Type: application/json" \
-d '{
"registrationIds": ["55555555", "666666666", "7777777777"],
}' \
https://api.netmera.com/tag/1.0/{tagName}/batch
Removing Devices from Tag

Following code is used to remove multiple devices from the tag. All devices will be unregistered from the given tag.

curl -X DELETE \
-H "X-netmera-api-key: ${API_KEY}" \
-H "Content-Type: application/json" \
-d '{
"registrationIds": ["55555555", "666666666", "7777777777"],
}' \
http://api.netmera.com/tag/1.0/{tagName}/batch
Tag Users by Custom Field

Following code is used to add given tag to the users who has a given custom field(s).

curl -X POST \
-H "X-netmera-api-key: ${API_KEY}" \
-H "Content-Type: application/json" \
-d '{
        "customFields": {
            "key1": "value1",
            "key2": "value2"
        }
}' \
https://api.netmera.com/tag/1.0/{tagName}/tagging

Back To Top

Downloads

Release Notes