Rich Push Widget

Android Push Notification

Push Notification helps you in sending event or alert to your app users even when they are not logged into app. App42 uses GCM (Google Cloud Messaging) to send Push Notification on Android devices. You can send push notification from UI console as well as can use APIs to send and schedule Push notification to your app users.You can also send Geo based Push Notification as well. App42 also gives you interesting insight about analytics of push messages too. Here are the few easy steps to get started with an App42 Android Push Notification using a sample project in a few minutes.

1. Prerequisite Setup

bullet Register with App42 platform

bullet Create an app once you are on Quick-start page after registration.

bullet If you are already registered, login to AppHQ console and create an app from App Manager -> App Create link.

bullet Create a project and get your Project Id from google developer console. It would be available in Overview section of your created project.

bullet Select your created project and click on APIs option in Google developer console and enable Google Cloud Messaging for Android service.

GoogleConsole1

bullet Click on Credentials from left menu -> Create New Key -> Server Key.

GoogleConsole2

bullet Keep Accept requests from these server IP addresses as blank and click on Create button

GoogleConsole3

bullet From AppHQ Management console click on Unified Notifications and click on Settings and view Android Setting as shown in below image:

App42AndroidSettingsSelect

bullet Select your app ,Click on Add Key if you have not added, Copy your server key under push key section which is generated in Google developer console in above step and submit it.

AppHQGCMKeysNew

2. Start building

bullet Download our sample project from GitHub Repo

bullet Unzip the downloaded file and import the project in eclipse and add google_play_service as a library.

bullet Open MainActivty.java file in which you need to pass the required information in onCreate and onStart method like API KEY & SECRET KEY which you have received after the success of app creation from AppHQ Console, Logged In User is basically that user for which you want to register your device to push & Google Project No is received after the success of project creation from Google Developer Console in the above steps.

@Override
public void onCreate(Bundle savedInstanceState) 
{
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_main);
	App42API.initialize(this,"<YOUR API KEY>","<YOUR SECRET KEY>");
	App42API.setLoggedInUser("<Logged In User>") ;
}

public void onStart() {
		super.onStart();
		if (App42GCMController.isPlayServiceAvailable(this)) {
			App42GCMController.registerOnGCM(MainActivity.this,
					"Your Google Project No", this);
		} else {
			Log.i("App42PushNotification",
					"No valid Google Play Services APK found.");
		}
	}

The Above snippet will do all the stuff for you seamlessly. Once app will get started it will register your app with GCM as well as with App42 platform for push notification usage. It uses storeDeviceToken method to register app with App42 server. This is only one time activity and will be done when app will be opened.

If you want to go in detail about the sample code, please see App42GCMController.java which does all GCM related work like registering with GCM and App42 server . Once your app gets registered with GCM,you will get regId, which you have to register using registerWithApp42 method defined in the class as shown below

public static void registerOnGCM(Context context,
			String googleProjectNo, App42GCMListener callBack) {
		GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context);
		String regId = App42GCMController.getRegistrationId(context);
		if (regId.isEmpty()) {
			registeronGCM(context, googleProjectNo, gcm, callBack);
		} else
			callBack.onGCMRegistrationId(regId);
	}
	//Method to get registered with App42 Platform
	public static void registerOnApp42(String userName,String deviceToekn,final App42GCMListener callBack){
		App42API.buildPushNotificationService().storeDeviceToken(userName, deviceToekn, new App42CallBack() {
			@Override
			public void onSuccess(Object arg0) {
				App42Response response=(App42Response) arg0;
				callBack.onRegisterApp42(response.getStrResponse());
			}
			
			@Override
			public void onException(Exception arg0) {
				// TODO Auto-generated method stub
				callBack.onApp42Response(arg0.getMessage());
			}
		});
	}

Android Manifest Settings

Following Permissions and entries are required to integrate Push Notification in your project. Sample Android Manifest contains these entries already however if you are integrating in your existing project put these lines in your Manifest too. You have to replace <YOUR_APPLICATION_PACKAGE_NAME> with the value of your package name. For example if your application package name is com.abc.myapp, you have to use it in place of <YOUR_APPLICATION_PACKAGE_NAME> defined in below Manifest

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="<YOUR_APPLICATION_PACKAGE_NAME>.permission.C2D_MESSAGE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<permission
    android:name="<YOUR_APPLICATION_PACKAGE_NAME>.permission.C2D_MESSAGE"
    android:protectionLevel="signature" />
 <receiver
            android:name="com.shephertz.app42.push.plugin.App42GCMReceiver"
            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="com.example.app42Sample" />
            </intent-filter>
        </receiver>
  <service android:name="com.shephertz.app42.push.plugin.App42GCMService" >
        </service>
		 <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
        <meta-data
            android:name="onMessageOpen"
            android:value="com.example.app42Sample.MainActivity" />

bullet Build your project and run.

After the success of app run, you can verify your registered user under Unified Notifications -> Push -> Users section as shown in below image.

PushRegisteredUsers

3. Sending Message to User

Once your app is registered you are ready to send message to your app user using following code snippet from any App42 SDK (Android/Java/WP etc)

From API

PushnotificationService pushnotificationService = App42API.buildPushnotificationService();    
PushNotification pushNotification = pushNotificationService.sendPushMessageToUser(userName,message);

From AppHQ Console

You can also send push messages to your registered app user directly from AppHQ console. To do this follow the simple steps:

bullet Login to AppHQ Management Console, Click on Unified Notification

bullet Click on Push -> Click on Users

bullet Select your App and user

bullet Click on Manage from table and click on send push button as shown in the below image:

PushFromConsole

Type your message, once you are done click on send button as show below. This will trigger a push notification message to your app user

SendPushFromConsole

4. Sending Message to iOS Device with Sound and Badge

If you want to send push message with sound and badge effect on iOS device, you have to pass JSON string in below format

PushnotificationService pushnotificationService = App42API.buildPushnotificationService();
String userName = "Nick";
 //Message format for iOS device with sound and badge  
String message = "{'alert':'Hi There...','badge':1,'sound':'default'}"; 
PushNotification pushNotification = pushNotificationService.sendPushMessageToUser(userName,message);

You can also do it from AppHQ by putting this JSON format in message text area for sending message to iOS device with sound and badge effect.

5. Sending Message to Channel

App42 Push notification also supports channel subscription model where user can subscribe on channel of his interest to receive the notification. You can send message to channel which will deliver message to all users who are subscribed to that channel. A channel can be created from AppHQ console. To do this follow the simple steps:

bullet Login to AppHQ Management Console, Click on Unified Notification

bullet Click on Push -> Click on Channels

bullet Select your App -> Click on Add channel button

AddChannelFromConsole

Once channel is created you can ask user for subscription on the channel. Below is the code snippet for the same

//
// First Subscribe User to Channel
//
String channelName = "cricket channel";  
String userName = "Nick";  
PushNotification pushNotification = pushNotificationService.subscribeToChannel(channelName,userName);  
//
// Now send message on the Channel
//
String channelName = "cricket channel";  
String message = "Mumbai Indians won IPL 6";  
PushNotification pushNotification = pushNotificationService.sendPushMessageToChannel(channelName,message); 

6. User Segmentation (Applying Filter)

App42 Push Notification Service has introduced API to target users who have specific profile/preference. This API requires user preference or profile persistence in Storage Service as a prerequisite. To identify a specific user segmentation, your app user profile or preference information should be saved on App42 cloud e.g. if you are building a music streaming app and you want to send push notifications to all those users who like Rock music, you should have preference of user stored in App42 cloud already and it can be done using Storage Service as shown below.

Saving User Preference

//Set Logged in User Name 
App42API.setLoggedInUser("USER_NAME"); 
String profileJSON = "{\"preference\":\"Rock\",\"age\":30,\"company\":\"ShepHertz\"}";
StorageService storageService = App42API.buildStorageService(); 
storageService.insertJSONDocument("DB_NAME", "COLLECTION_NAME", profileJSON );

Sending Push to Segmented User

Once your app user’s profile/preference information is saved, you can send Push Notification to the segmented user who meets specific criteria (Assuming your app user is already subscribed for push notification. For example, here you can send Push Notification to segmented users who likes Rock music as explained below.

Query targetQuery = QueryBuilder.build("preference","Rock", Operator.EQUALS);
String message = "New Album of Rock Music has just Arrived. Please check it out here!!";
PushNotificationService pushNotificationService = App42API.buildPushNotificationService();
pushNotificationService.sendPushToTargetUsers(message, "DB_NAME", "COLLECTION_NAME", targetQuery);

7. Scheduling Message to User

You can also schedule message to your app user on specified time from AppHQ console. To do this follow the simple steps:

bullet Login to AppHQ Management Console, Click on Unified Notification

bullet Click on Push -> Click on Users

bullet Select your App -> select target user and click on manage

bullet Click on Send button and type your message in pop up and pass your time to schedule the message.

SchedulePushMessageFromConsole

8. Scheduling message to Channel

Message scheduling on channel can be done in similar way. To do this follow the simple steps:

bullet Login to AppHQ Management Console, Click on Unified Notification

bullet Click on Push -> Click on Channels

bullet Select your App -> select target channel and click on manage

bullet Click on Send Push button and type your message in pop up and pass your time to schedule the message.

SchedulePushMessageFromConsole

9. Configuring Notification UI

Push notification received on user device can be configured and can be controlled from the code written in generateNotification method as shown below

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
				this).setSmallIcon(R.drawable.ic_stat_gcm)
				.setContentTitle(title)
				.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
				.setContentText(msg).setWhen(when).setNumber(++msgCount)
				.setLights(Color.YELLOW, 1, 2).setAutoCancel(true)
				.setDefaults(Notification.DEFAULT_SOUND)
				.setDefaults(Notification.DEFAULT_VIBRATE);

10. Opening Activity on Message Click

You can specify which Activity should be opened once user clicks on message. Its configured inside AndroidManifest.xml as shown below

    <meta-data
            android:name="onMessageOpen"
            android:value="com.example.app42Sample.MainActivity" />

11. Doing Push Analytics

Push notification goes from App42 server to GCM server and then device. Delivery of Push notification is not guaranteed from GCM to device and it is stated as best effort. Once it is delivered on user device, there might be a chance that user clears it without actually Opening the message.

Using App42 Push Analytics, you can track how many push notification was sent from your side, how many were delivered and how many were opened by the user. You can see these analytics from AppHQ console which will give a better insight of push notification campaign.

If you want to track push message read/opened event you have to simply put following snippet after Message is clicked and lands to your activity. This will enable tracking of push message and analytics can be seen from AppHQ console.

App42API.buildLogService().setEvent("Message", "Opened", new App42CallBack() {
	public void onSuccess(Object arg0) {
		// TODO Auto-generated method stub
	}
	public void onException(Exception arg0) {
		// TODO Auto-generated method stub
	}
}); 

12. Send Multilingual Push Notification

Once your device is registered for Push Notification you are ready to send multilingual(UTF-8) push message to your app user using following code snippet from any App42 SDK (Android/Java/WP etc)

String userName = "Nick";
String message = "Message which you have to send";
HashMap<String, String> otherMetaHeaders = new HashMap<String, String>();
otherMetaHeaders.put("dataEncoding", "true");
pushNotificationService.setOtherMetaHeaders(otherMetaHeaders)
pushNotificationService.sendPushMessageToUser(userName, message, new App42CallBack() {
	public void onSuccess(Object response) 
	{
		PushNotification pushNotification  = (PushNotification)response;
		System.out.println("userName is " + pushNotification.getUserName());  
		System.out.println("Message is " + pushNotification.getMessage()); 
		System.out.println("Expiry is"+pushNotification.getExpiry());
	}
	public void onException(Exception ex) 
	{
		System.out.println("Exception Message"+ex.getMessage());
	}
});   

13. Migrate Old GCM Configuration to new GCM

If you have integrated Push Notification using old API of GCM, you have to migrate to new Google Cloud Messaging API. Here are some necessary steps which you have to follow:

bullet Add Google Play Service as a library project and remove GCM.jar file from libs folder

bullet Update android_support library from the new Sample application

bullet copy plugin classes of sample project(com\shephertz\app42\push\plugin : package) into your project

bullet Remove existing App42GCMService and App42GCMReceiver class from existing project

bullet Modify App42GCMService and App42GCMReceiver path and add metaData for MeesageOpen and google_play_library version in AndoidManifest.xml of your application as mentioned in above steps

bullet Remove “Util.registerWithApp42(“<Your Google Project No>”)” from onStart as well from Util class.

bullet Modify Your MainActivity with use of following code snippet.

@Override
	public void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		App42API.initialize(this,"<YOUR API KEY>","<YOUR SECRET KEY>");
		App42API.setLoggedInUser("<Logged In User>") ;
	}
	public void onStart() {
		super.onStart();
		if (App42GCMController.isPlayServiceAvailable(this)) {
			App42GCMController.registerOnGCM(MainActivity.this,
					"Your Google Project No", this);
		} else {
			Log.i("App42PushNotification",
					"No valid Google Play Services APK found.");
		}
	}

bullet Also implement App42GCMListener interface and copy implemented method from the updated sample e.g.

//Error on GCM registration

@Override
	public void onError(String errorMsg) {
		
	}

//gcmRegId callback from GCM
	@Override
	public void onGCMRegistrationId(String gcmRegId) {
		App42GCMController.storeRegistrationId(this, gcmRegId);
		if(!App42GCMController.isApp42Registerd(MainActivity.this))
		App42GCMController.registerOnApp42(App42API.getLoggedInUser(), gcmRegId, this);
	}
	@Override
	public void onApp42Response(final String responseMessage) {
		// TODO Auto-generated method stub
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
			}
		});
	}

//Registration on App42 Succeeded
	@Override
	public void onRegisterApp42(final String responseMessage) {
		// TODO Auto-generated method stub
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				App42GCMController.storeApp42Success(MainActivity.this);
			}
		});
	}

For more details of Push Notification Documentation