Rich Push Widget

Android Push Notifications

This tutorial will help you configure your Android app to send and receive push notifications. App42 Cloud API provides push notifications using GCM (Google Cloud Messaging). You may then send push notifications from AppHQ console as well as shoot notifications by simply using APIs to your app users. The beauty of App42 Push is that you can schedule notifications and even send location based messages as well. Along with sending push notifications, you can also capture detailed insights of the response your push messages with the analytics. Please follow these easy steps to get started with the App42 platform and start sending push messages within minutes.

1. Prerequisite Setup

bullet Sign up with App42 platform to create your first app after choosing App42 Cloud APIs and Android as your preferred platform

bullet Connect your app with App42 by following the steps mentioned after you download the Android SDK

bullet If you have created your first app already, simply login to AppHQ console to continue

bullet Create a project in google developer console. Fetch your Project ID from the Overview section of your created project

bullet Select your created project and click on APIs option in GCM to enable Google Cloud Messaging for Android service

Enable GCM Settings

bullet To get your server key, click on Credentials and then on Create New Key

Enable Cloud Messaging

Create Credentials

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

Create Server Key

bullet Now switch to AppHQ console click on Unified Notifications and then on Settings to view Android Settings as shown below:

Adding Android Settings

bullet Select your app, click on Add Key and insert the server key that was generated in google developer console and submit it

Configuring Android push keys

2. Start building

bullet Download our [sample project here] (https://github.com/shephertz/App42-Android-Push-Sample/archive/master.zip)

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 would have to pass the required information in onCreate and onStart method like API KEY & SECRET KEY which you must have received after the completion of integration steps in 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 code snippet provided will carry out most of the important work for you conveniently. Once your app gets started, it will register your application with GCM as well as with App42 platform in order to send push notifications. Just to let you know, it uses storeDeviceToken method to register your application with the App42 server. This is just a one time activity and will be done automatically whenever the app is opened.

If you want to know the details about the sample code, please go through App42GCMController.java which basically takes care of all the GCM related tasks. Once your application gets registered with GCM, you will get regId, which you will 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

The next step is to include the following permissions and entries that are necessary to complete the integration process of Push Notifications in your project. Sample Android Manifest contains these entries already, however, if you are integrating in your existing project then you would have to put the following code in your Manifest too. Just replace <YOUR_APPLICATION_PACKAGE_NAME> with the value of your package name. For example, if your application package name is com.abc.myapp, use it in place of <YOUR_APPLICATION_PACKAGE_NAME> defined in the 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 successful run of your app, you can verify your registered users under Unified Notifications -> Push -> Users section as shown below.

Registered Users list

3. Sending Message to User

Once your application is successfully registered, you may start sending push to your users using the following code snippet from any of the App42 SDKs

From API

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

From AppHQ Console

You may even send push notifications to your registered app users directly through AppHQ console. Follow these simple steps to send your first push:

bullet Click on Unified Notifications

bullet Click on Push -> Click on Users

bullet Select your App and users

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

Action on Registered users

Enter your push notification copy and click on send button as shown below. This will trigger the push notification to your app users

Send User Push from Console

4. Sending Message to an iOS Device with Sound and Badge

Doesn’t matter if you have registered your application for Android Push Notifications, you may send push with sound and badges to iOS devices as well. Just pass the following JSON string in the following 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 may also do it through AppHQ console by putting this JSON format in message text area for sending message to an iOS device with sound and badge effects

5. Sending Message to a Channel

App42 Push also supports subscription based model where users can subscribe to a channel of their interest to receive notifications related only to that channel. You can send message to a channel which will deliver your message to all the users who have subscribed to that particular channel.

//
// 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 enables you to target users based on their specific profile or preference. This feature requires user preference or profile persistence in Storage Service as a prerequisite. To identify a specific user segmentation, the user profiles or preference information should be saved on App42 cloud. For example, if you are building a media app and would like to send push notifications to all the users who like sports news, you should have the preference of those users stored in App42 cloud already. This can be achieved 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 Users

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 = "Did you watch the last night's match? We are excited to share the analysis!";
PushNotificationService pushNotificationService = App42API.buildPushNotificationService();
pushNotificationService.sendPushToTargetUsers(message, "DB_NAME", "COLLECTION_NAME", targetQuery);

7. Scheduling Message to User

You may even schedule message to your app users on a particular time through AppHQ console. Simply follow these easy steps:

bullet 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 the pop up and enter the desired time to schedule the message

Schedule Push Message From Console

8. Scheduling message to Channel

Scheduling future push notifications on channels can also be done in the similar way. To do this follow the simple steps:

bullet 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 button and type your message in the pop up and enter the desired time to schedule the message

Schedule Push Message From Console

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. Analyzing Push Notifications

Push notification is shot from the App42 server to GCM server and then to the devices. The delivery of the push is not guaranteed by GCM to the devices and it is stated as a best effort. Once it is delivered on the users’ devices, there are chances that a user clears it without actually reading the message

Using App42 Push Analytics, you can keep a track of how many push notifications were sent by you and out of them how many were delivered and subsequently opened by the users. You can monitor all this from the AppHQ console which will give you a better and detailed insight of the sent push notifications.

If you would like to track how many push messages were read/opened, you would have to put the following snippet after the message is clicked and lands to your activity. This will enable the tracking of push notifications and analytics can be checked 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

By registering your application with App42 you are automatically empowered to send multilingual(UTF-8) push messages to your app user using the following code snippet from any of the App42 SDKs

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 Notifications 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 and advanced features, please check out the Push Notification Documentation.