Skip to main content

GCM Online Notification

GCM - Online PushNotification For Android.


Only send Text send.


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 console click on Push Notification and select Android Settings in Settings option.
bullet Select your app and copy server key that is generated in Google developer console in above step and submit it.
AppHQGCMKeys

2. Start building

bullet Download sample project from our GitHub Repo
bullet Unzip the downloaded file and import it in eclipse.
bullet Open MainActivty.java file in and pass required information in onCreate method as shown below
  1. @Override  
  2.     public void onCreate(Bundle savedInstanceState) {  
  3.         super.onCreate(savedInstanceState);  
  4.         setContentView(R.layout.activity_main);  
  5.         App42API.initialize(this,"<YOUR API KEY>","<YOUR SECRET KEY>");  
  6.         App42API.setLoggedInUser("<Logged In User>") ;  
  7.         Util.registerWithApp42("<Your Google Project No>");  
  8.     }  
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 App42GCMService.java which does all GCM related work like registering with GCM and App42 server and generating notification. This class overrides GCMBaseIntentService class and overrides onMessage and onRegister method. Once your app gets registered with GCM, its onRegister method gets invoked, which further calls registerWithApp42 method defined in the class as shown below
  1. @Override  
  2.     protected void onRegistered(Context arg0, String regId) {  
  3.         Log.i(TAG, "Device registered: regId = " + regId);  
  4.         registerWithApp42(regId);  
  5.     }  
  6.     //Method to get registered with App42 Platform  
  7.     private void registerWithApp42(String regId) {  
  8.         App42Log.debug(" Registering on App42 Server ....");  
  9.         App42API.buildPushNotificationService().storeDeviceToken(App42API.getLoggedInUser(), regId, new App42CallBack() {  
  10.             @Override  
  11.             public void onSuccess(Object paramObject) {  
  12.                 App42Log.debug(" ..... Registration Success ....");  
  13.                 GCMRegistrar.setRegisteredOnServer(App42API.appContext, true);  
  14.             }  
  15.             @Override  
  16.             public void onException(Exception paramException) {  
  17.                 App42Log.debug(" ..... Registration Failed ....");  
  18.                 App42Log.debug("storeDeviceToken :  Exception : on startup " +paramException);  
  19.             }  
  20.         });  
  21.     }  

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
  1. <uses-permission android:name="android.permission.INTERNET" />  
  2. <uses-permission android:name="android.permission.VIBRATE" />  
  3. <uses-permission android:name="android.permission.WAKE_LOCK" />  
  4. <uses-permission android:name="android.permission.GET_ACCOUNTS" />  
  5. <uses-permission android:name="android.permission.WAKE_LOCK" />  
  6. <uses-permission android:name="<YOUR_APPLICATION_PACKAGE_NAME>.permission.C2D_MESSAGE" />  
  7. <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />  
  8. <permission  
  9.     android:name="<YOUR_APPLICATION_PACKAGE_NAME>.permission.C2D_MESSAGE"  
  10.     android:protectionLevel="signature" />  
  11. <receiver  
  12.     android:name="com.example.app42sample.App42GCMReceiver"  
  13.     android:permission="com.google.android.c2dm.permission.SEND" >  
  14.     <intent-filter>  
  15.         <action android:name="com.google.android.c2dm.intent.RECEIVE" />  
  16.         <action android:name="com.google.android.c2dm.intent.REGISTRATION" />  
  17.         <category android:name="<YOUR_APPLICATION_PACKAGE_NAME>" />  
  18.     </intent-filter>  
  19. </receiver>  
  20. <service android:name="com.example.app42sample.App42GCMService">  
  21.     <meta-data android:name="onMessageOpen"   
  22.         android:value="<ACTIVITY_TO_BE_OPENED_ON_MESSAGE_CLICK>" />  
  23. </service>  

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
  1. PushnotificationService pushnotificationService = App42API.buildPushnotificationService();      
  2. 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, go to AppHQ console and click on Push Notification -> Click on User Link -> Select your App -> select your user from table and click on send message button. This will open a pop up to type your message, once you are done click on send button. This will trigger a push notification message to your app user.
PushFromConsole

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
  1. PushnotificationService pushnotificationService = App42API.buildPushnotificationService();  
  2. String userName = "Nick";  
  3.  //Message format for iOS device with sound and badge  
  4. String messsage = "{'alert':'Hi There...','badge':1,'sound':'default'}";   
  5. 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. Go to Push Notification ->Channel -> Select your App -> Click on Create Channel button
Once channel is created you can ask user for subscription on the channel. Below is the code snippet for the same
  1. //  
  2. // First Subscribe User to Channel  
  3. //  
  4. String channelName = "cricket channel";    
  5. String username = "Nick";    
  6. PushNotification pushNotification = pushServiceNotification.subscribeToChannel(channelName,username);    
  7. //  
  8. // Now send message on the Channel  
  9. //  
  10. String channelName = "cricket channel";    
  11. String message = "Mumbai Indians won IPL 6";    
  12. 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
  1. //Set Logged in User Name   
  2. App42API.setLoggedInUser("USER_NAME");   
  3. String profileJSON = "{\"preference\":\"Rock\",\"age\":30,\"company\":\"ShepHertz\"}";  
  4. StorageService storageService = App42API.buildStorageService();   
  5. 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.
  1. Query targetQuery = QueryBuilder.build("preference","Rock", Operator.EQUALS);  
  2. String message = "New Album of Rock Music has just Arrived. Please check it out here!!";  
  3. PushNotificationService pushNotificationService = App42API.buildPushNotificationService();  
  4. 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, got to Push Notification -> Click on User link -> Select your app -> select target users/device and click on schedule message button. Now type your message in pop up and pass your time to schedule the message.

8. Scheduling message to Channel

Message scheduling on channel can be done in similar way. Go to Push Notification -> Click on Channel link -> Select your app -> select target channel and click on schedule message button. Now type your message in pop up and pass your time to schedule the message.

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
  1. Notification notification = new NotificationCompat.Builder(context)  
  2.         .setContentTitle(title)  
  3.         .setContentText(message)  
  4.         .setContentIntent(intent)  
  5.         .setSmallIcon(icon)  
  6.         .setWhen(when)  
  7.         .setLargeIcon(getBitmapFromURL(LARGE_IMAGE_URL))  
  8.         .setLights(Color.YELLOW, 12)  
  9.         .setAutoCancel(true)  
  10.         .build();  

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
  1. <service android:name="com.example.app42sample.App42GCMService" >  
  2.       <meta-data android:name="onMessageOpen" android:value="com.example.app42sample.MessageActivity" />  
  3. </service>  

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.
  1. App42API.buildLogService().setEvent("Message""Opened"new App42CallBack() {  
  2.                         public void onSuccess(Object arg0) {  
  3.                             // TODO Auto-generated method stub  
  4.                         }  
  5.                         public void onException(Exception arg0) {  
  6.                             // TODO Auto-generated method stub  
  7.                         }  
  8.                     });   





Comments

Popular posts from this blog

Laravel Free Admin Panel UI and Code

Thanks for share  https://github.com/the-control-group/voyager V oyager - The Missing Laravel Admin Made with  ❤️  by  The Control Group Website & Documentation:  https://voyager.devdojo.com/ Video Tutorial Here:  https://voyager.devdojo.com/academy/ Join our Slack chat:  https://voyager-slack-invitation.herokuapp.com/ View the Voyager Cheat Sheet:  https://voyager-cheatsheet.ulties.com/ Laravel Admin & BREAD System (Browse, Read, Edit, Add, & Delete), supporting Laravel 6 and newer! Want to use Laravel 5? Use  Voyager 1.3 Installation Steps 1. Require the Package After creating your new Laravel application you can include the Voyager package with the following command: composer require tcg/voyager 2. Add the DB Credentials & APP_URL Next make sure to create a new database and add your database credentials to your .env file: DB_HOST=localhost DB_DATABASE=homestead DB_USERNAME=homestead DB...

How To Install And Setup Laravel Latest Version On Windows 10 Using XAMPP

How to install Laravel on Windows using XAMPP Laravel, one of the best PHP framework is getting more popular among developers all around the world. The Model-View-Controller architecture and blade templating engine made Laravel simple and powerful. Here we are going to discuss the steps of installation and setup of Laravel 5.7 on Windows 10 using XAMPP. Installation Follow the steps below to start installing Laravel 5.7 on Windows 10: 1. Install XAMPP XAMPP is the most popular PHP development environment.XAMPP is a completely free, easy to install Apache distribution containing MariaDB, PHP, and Perl. The XAMPP open source package has been set up to be incredibly easy to install and to use. XAMPP can be easily installed using the link below. https://www.apachefriends.org/download.html Laravel 5.7 requires PHP >= 7.1.3. Download the latest version (7.3.3/PHP 7.3.3). I have shown some screenshots of the installation steps below. 2. Start Apache and MySQ...
Share Application - Any social  app  Facebook,Twitter,Instagram,Youtube,Google+....etc.                                      Pate Prashant    Android Code For share any application. Share code for Video,Image,Text.  share on (Twitter,Facebook,Instagram,Google+,Youtube) Some packeges of application name Application Name                                                Package Name Twitter                         ...