Monday, May 27, 2013

Push Notification

Push notifications provides a way to notify your mobile application on new message or event that is related to your application. Push notification are received and displayed regardless to the application running status. 
When a device receive push notification the application icon and a message appears on the device status bar. If the user press the notification message he is directed to your application.

Using Parse.com as notifications server

In this post i will show how to use push notifications from Parse.com. 
The tutorial will demonstrate:
1.  How to receive the notification and display it
2.  How to implement popup message upon receiving push notification. (I am leaving out the decision what is prefer by the users status bar notification or popups)

The first step is to have a Parse.com account  and open and application in the Parse.com dashboard.
Create Android empty project and add Parse SDK jar to your lib directory.
On your Android application:
1. Initialize parse SDK with your application,client keys.
2. Register to Parse notification services:

 protected void onCreate(Bundle savedInstanceState) {  
           super.onCreate(savedInstanceState);  
           setContentView(R.layout.activity_main);  
         //Parse SDK Init  
           Parse.initialize(this, Applicatio Id, Client ID);  
           PushService.setDefaultPushCallback(this, MainActivity.class);  
           ParseInstallation.getCurrentInstallation().saveInBackground();  
      }  

In the manifest file add the following permissions:

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

Register receiver just before the closing </application> tag :


 <receiver android:name="com.parse.ParseBroadcastReceiver" >  
       <intent-filter>  
         <action android:name="android.intent.action.BOOT_COMPLETED" />  
         <action android:name="android.intent.action.RECEIVE_BOOT_COMPLETED" />  
         <action android:name="android.intent.action.USER_PRESENT" />  
       </intent-filter>  
 </receiver>  

At this point your application is ready for receiving push notification in order to test it go to Parse dashboard and select Push notification tab and send notification .

Check the device /emulator status bar to see the notification message.

Implementing Push Notification Receiver

Lets implement our own receiver that will open popup dialog. Parse API provide way to send the push notification as JSON object that encapsulate more data inside the notification. The supported JSON object includes the intent that should be triggered when the notification received.

First change the manifest and add the following receiver :


 <receiver android:name="com.iakremera.pushdemo.MyCustomReceiver" >  
       <intent-filter>  
         <action android:name="android.intent.action.BOOT_COMPLETED" />  
         <action android:name="android.intent.action.USER_PRESENT" />              
         <action android:name="com.iakremera.pushdemo.UPDATE_STATUS" />  
       </intent-filter>  
 </receiver>  

The bold action represent the information that will be sent from the server in order to fire the intent.
The receiver code look like :

 public class MyCustomReceiver extends BroadcastReceiver {  
      private static final String TAG = "MyCustomReceiver";  
      @Override  
      public void onReceive(Context context, Intent intent) {  
           try {  
                if (intent == null)  
                {  
                     Log.d(TAG, "Receiver intent null");  
                }  
                else  
                {  
                     String action = intent.getAction();  
                     Log.d(TAG, "got action " + action );  
                     if (action.equals("com.iakremera.pushdemo.UPDATE_STATUS"))  
                     {  
                          String channel = intent.getExtras().getString("com.parse.Channel");  
                          JSONObject json = new JSONObject(intent.getExtras().getString("com.parse.Data"));  
                          Log.d(TAG, "got action " + action + " on channel " + channel + " with:");  
                          Iterator itr = json.keys();  
                          while (itr.hasNext()) {  
                               String key = (String) itr.next();  
                               if (key.equals("customdata"))  
                               {  
                                    Intent pupInt = new Intent(context, ShowPopUp.class);  
                                    pupInt.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK );  
                                    context.getApplicationContext().startActivity(pupInt);  
                               }  
                               Log.d(TAG, "..." + key + " => " + json.getString(key));  
                          }  
                     }  
                }  
           } catch (JSONException e) {  
                Log.d(TAG, "JSONException: " + e.getMessage());  
           }  
      }  
 }  

The receiver verify the action that is required matches the registered one and start the ShowPopUp activity. The ShowPopUp activity simply display the message as dialog widow. In order to achieve it flow the steps.

1. There are couple of ways to define popup window in android I choose to create the popup as activity that is launched as dialog. Define layout file popupdialog.xml


 <?xml version="1.0" encoding="utf-8"?>  
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   android:id="@+id/menuEditItemLayout"  
   android:layout_width="match_parent"  
   android:layout_height="match_parent"  
   android:orientation="vertical" >  
   <LinearLayout  
     android:layout_width="250dp"  
     android:layout_height="wrap_content"  
     android:gravity="center" >  
     <TextView  
       android:id="@+id/durationTitle"  
       android:layout_width="wrap_content"  
       android:layout_height="wrap_content"  
       android:layout_alignParentTop="true"  
       android:layout_gravity="center"  
       android:text="Task"  
       android:textColor="@android:color/holo_blue_dark"  
       android:textSize="25sp" />  
   </LinearLayout>  
   <RelativeLayout  
     android:layout_width="match_parent"  
     android:layout_height="48dp"  
     android:layout_alignParentBottom="true">  
     <View  
       android:layout_width="match_parent"  
       android:layout_height="1dip"  
       android:layout_marginLeft="4dip"  
       android:layout_marginRight="4dip"  
       android:background="?android:attr/dividerVertical"  
       android:layout_alignParentTop="true"/>  
     <View  
       android:id="@+id/ViewColorPickerHelper"  
       android:layout_width="1dip"  
       android:layout_height="wrap_content"  
       android:layout_alignParentTop="true"  
       android:layout_alignParentBottom="true"  
       android:layout_marginBottom="4dip"  
       android:layout_marginTop="4dip"  
       android:background="?android:attr/dividerVertical"   
       android:layout_centerHorizontal="true"/>  
     <Button  
       android:id="@+id/popOkB"  
       android:layout_width="wrap_content"  
       android:layout_height="wrap_content"  
       android:layout_alignParentLeft="true"  
       android:layout_alignParentTop="true"  
       android:layout_toLeftOf="@id/ViewColorPickerHelper"  
       android:background="?android:attr/selectableItemBackground"  
       android:text="@android:string/cancel"   
       android:layout_alignParentBottom="true"/>  
     <Button  
       android:id="@+id/popCancelB"  
       android:layout_width="wrap_content"  
       android:layout_height="match_parent"  
       android:layout_alignParentRight="true"  
       android:layout_alignParentTop="true"  
       android:background="?android:attr/selectableItemBackground"  
       android:text="@android:string/ok"   
       android:layout_alignParentBottom="true"   
       android:layout_toRightOf="@id/ViewColorPickerHelper"/>  
   </RelativeLayout>  
 </LinearLayout>  

2. The activity implementation:

 public class ShowPopUp extends Activity implements OnClickListener {  
      Button ok;  
      Button cancel;  
      boolean click = true;  
      @Override  
      public void onCreate(Bundle savedInstanceState) {  
           super.onCreate(savedInstanceState);  
           setTitle("Cupon");  
           setContentView(R.layout.popupdialog);  
           ok = (Button)findViewById(R.id.popOkB);  
           ok.setOnClickListener(this);  
           cancel = (Button)findViewById(R.id.popCancelB);  
           cancel.setOnClickListener(this);  
      }  
      @Override  
      public void onClick(View arg0) {  
           // TODO Auto-generated method stub  
           finish();  
      }  
 }  

3. Register the activity in the manifest file

 <activity  
      android:name="com.iakremera.pushnotificationdemo.ShowPopUp"  
      android:label="@string/app_name"  
      android:theme="@android:style/Theme.Holo.Light.Dialog" >  
 </activity>  

In order to send the notification you can send the following JSON object (this is only an example).
In order to launch an intent the JSON object should not include the "alert" field.  The notification text should be inserted into  user defined field inside the JSON object (like "customdata").

In the attached source code the notification is sent from the device.
.
 {  
 "action":"com.iakremera.pushnotificationdemo.UPDATE_STATUS",  
 "customdata":"My string"  
 }  

The screenshot :

The source code for this demo project can be downloaded here.
More options using Parse.com push notification can be found here.

89 comments:

  1. Hi Itai Ahiraz, through this am getting notification but unable to read the message which am sending from dashboard.can you please suggest me how to read and display parse notification on activity when i clicked on that message in notification bar

    Thanks in advance.........

    ReplyDelete
    Replies
    1. Hi
      You need to send your activity Intenet (see above in the onReceiver implementation). You should also run your app at least one time after downloading it to your device.

      Delete
  2. Thanks for providing the information
    For more information please visit here push notification server.

    ReplyDelete
  3. Thanks for sharing info and i also tell some thing about Parse. Parse provide 3 unique functionality namely parse push, Parse analytic and Parse core that make it stand different from others. Parse push helps in scheduling whereas parse core helping in saving the data or content.

    ReplyDelete
  4. Hi Itai Ahiraz, I tried your source code for push notification and its working great. Thanks for sharing.
    Android Training Chennai

    ReplyDelete
  5. This comment has been removed by the author.

    ReplyDelete
  6. Hi ,I tried your example it works great but the only problem is that I just got "Task" in dialog instead of my notification message that I sent it. Please help me to display my notification message instead of "Task". I really appreciated your answer and thanks for information :)

    ReplyDelete
  7. Android Training in Chennai

    Your blog is really useful for me. Thanks for sharing this useful blog..Suppose if anyone interested to learn Android Course in Chennai please visit fita academy which offers best Android Training in Chennai at reasonable cost.

    Android Training Institutes in Chennai

    ReplyDelete
  8. Thanks for sharing this valuable information to our vision. You have posted a trust worthy blog keep sharing.Nice article i was really impressed by seeing this article, it was very interesting and it is very useful for me.. Android Training in chennai | Android Training chennai | Android course in chennai | Android course chennai

    ReplyDelete
  9. I gathered a lot of information through this article.Every example is easy to understandable and explaining the logic easily.Thanks! Phonegap training in chennai | Phonegap training chennai | Phonegap course in chennai | Phonegap course chennai

    ReplyDelete
  10. Thanks for sharing this info but I just want to ask tht is it possible not to message frm the parse dashboard but the code embedded in the project tht should be triggered on the click event of a button.

    ReplyDelete
  11. This comment has been removed by the author.

    ReplyDelete
  12. Excellent post!!! Training on android technology helps professionals to establish a career in android mobile application development. Android Training Institute in Chennai Best Android Training institute in Chennai

    ReplyDelete
  13. Thanks for sharing this valuable information to our vision. You have posted a trust worthy blog keep sharing.
    Regards,
    Informatica courses in Chennai|Informatica institutes in Chennai|Salesforce training institute in Chennai

    ReplyDelete
  14. Nice info.Thanks for sharing such great valuable information.Really your blog is very informative.Mobile App Developers in Bangalore| Graphic Designers in Bangalore

    ReplyDelete
  15. Thanks for sharing this informative blog. Suppose if anyone interested to learn android in chennai, best android training institute!

    ReplyDelete
  16. This comment has been removed by the author.

    ReplyDelete
  17. This information is impressive..I am inspired with your post writing style & how continuously you describe this topic. After reading your post,thanks for taking the time to discuss this, I feel happy about it and I love learning more about this topic
    best ccPlus training institute

    ReplyDelete
  18. This comment has been removed by the author.

    ReplyDelete
  19. This comment has been removed by the author.

    ReplyDelete
  20. This comment has been removed by the author.

    ReplyDelete
  21. Thanks for sharing this valuable information to our vision. You have posted a trust worthy blog keep sharing.
    oracle dba training in chennai

    ReplyDelete

  22. Hi, probably our entry may be off topic but anyways, I have been surfing around your blog and it looks very professional. It’s obvious you know your topic and you appear fervent about it. I’m developing a fresh blog plus I’m struggling to make it look good, as well as offer the best quality content. I have learned much at your web site and also I anticipate alot more articles and will be coming back soon. Thanks you.

    Android App Development Training in Chennai

    ReplyDelete

  23. Thank you very much for providing this notes it has been very much useful for writing the code.

    best android training in bangalore

    ReplyDelete
  24. Great post! I am see the great contents and step by step read really nice information.I am gather this concepts and more information. It's helpful for me my friend. Also great blog here with all of the valuable information you have.
    Websphere Training in Chennai

    ReplyDelete
  25. It's extraordinarily impressive I'll be seen that many of the bloggers relevant android community that the time I read that's your suggestions helped me and define the new thing. pretty understandable helpful content.
    Dot Net Training in Chennai
    .Net Training Institute in Chennai
    Hadoop Training in Chennai with Placement
    Best Selenium Training in Chennai

    ReplyDelete
  26. This comment has been removed by the author.

    ReplyDelete
  27. This is really very interesting. This blog contain too much information about parse android app development.

    ReplyDelete
  28. cse projects in chennai and provides the best project for IEEE students. The stage utilizes the protest arranged eee projects in chennai and ece projects in chennai.

    ReplyDelete
  29. Really very nice blog information for this one and more technical skills are improve,i like that kind of post.
    advanced excel training in bangalore | Devops Training in Chennai

    ReplyDelete
  30. Hi,

    Thanks for sharing a very interesting article about Push Notification. This is very useful information for online blog review readers. Keep it up such a nice posting like this.

    Regards,
    WondersMind,
    Web Design Company Bangalore

    ReplyDelete


  31. Whoa! I’m enjoying the template/theme of this website. It’s simple, yet effective. A lot of times it’s very hard to get that “perfect balance” between superb usability and visual appeal. I must say you’ve done a very good job with this.


    AWS Training in BTM Layout |Best AWS Training in BTM Layout

    AWS Training in Marathahalli | Best AWS Training in Marathahalli

    ReplyDelete
  32. Thanks for your informative article, Your post helped me to understand the future and career prospects & Keep on updating your blog with such awesome article.
    angularjs Training in bangalore

    angularjs Training in bangalore

    angularjs Training in chennai

    automation anywhere online Training

    angularjs interview questions and answers

    ReplyDelete
  33. Hi,

    Thanks for sharing a very interesting article about Push Notification. This is very useful information for online blog review readers. Keep it up such a nice posting like this.

    Regards,
    WondersMind,
    Web Design Company Bangalore

    ReplyDelete
  34. Thanks for information , This is very useful for me.
    Keep sharing Lean Six Sigma Green Belt Training Bangalore


    ReplyDelete
  35. 1. many peoples want to join random whatsapp groups . as per your demand we are ready to serve you whatsapp group links . On this website you can join unlimited groups . click and get unlimited whatsapp group links 18+

    ReplyDelete

  36. I like viewing web sites which comprehend the price of delivering the excellent useful resource Python training in pune free of charge. I truly adored reading your posting. Thank you!

    ReplyDelete
  37. Thanks for the points shared in your blog. One more thing I would like to talk about is that fat reduction is not information about going on a celebrity diet and trying to shed as much weight as you can in a couple of weeks.The most effective way to lose weight is by getting it bit by bit and right after some basic recommendations which can help you to make the most from your attempt to shed weight. You may understand and be following some of these tips, although reinforcing information never damages. Mahapolice , Majhi naukri, Govnokri, Mpsc world, NMK, Jobchjob, Freshersvoice, Pavitra Portal, Mahavitaran, Mahakosh, Msrtc exam, Mahapariksha, Mahapolice, Mahakosh, Ongc Recruitment, Free Job Alert.

    ReplyDelete
  38. Thanks for your informative article,Your post helped me to understand the future and career prospects & Keep on updating your blog with such awesome article.
    web designing training in
    AWS training in Chennai

    AWS Online Training in Chennai

    AWS training in Bangalore

    AWS training in Hyderabad

    AWS training in Coimbatore

    AWS training

    ReplyDelete
  39. This comment has been removed by the author.

    ReplyDelete
  40. I tried your example it works great but the only problem is that I just got "Task" in dialog instead of my notification message that I sent it. Please help me to display my notification message instead of "Task". I really appreciated your answer and thanks for information :)
    java training in chennai

    java training in omr

    aws training in chennai

    aws training in omr

    python training in chennai

    python training in omr

    selenium training in chennai

    selenium training in omr

    ReplyDelete
  41. It's been our pleasure to inform you that our institution is offering a great deal by giving CS executive classes and a free CSEET class only for those who are interested in gaining knowledge. So what are you waiting for contact us or visit our website at https://uniqueacademyforcommerce.com/

    ReplyDelete
  42. Aximtrade Mt4 Download Is The Foreign Exchange Trading Platform Of Choice For Over 100,000 Investors Around The World. It's The Place To Trade Forex And Cfds On Global Markets, With Access To A Huge Range Of Assets And Features All In One Place.

    ReplyDelete
  43. Want To Trade Forex With AVATRADE REVIEW ? Read This Blog First To Find Out About The Best Forex Trading Conditions. We Review The Most Popular Forex Brokers And Tell You What You Need To Know.

    ReplyDelete
  44. This post is so interactive and informative.keep update more information...
    Java Training in Tambaram
    java course in tambaram

    ReplyDelete
  45. I want the world to know about where to invest their hard earned money and get fruitful returns. If one is looking forward of investing he can go into investment of crypto coins.
    You can invest in Fudxcoin company that deals in the selling and purchasing of Crypto Currency. It is a reliable company. One need not doubt in investing in it as i have also bought crypto currency from it and feeling very satisfied with their services.
    crypto currency block chain technology

    ReplyDelete
  46. Very informative blog . But i also want the world to know There is one company in my mind, its name is AFM Logistics pvt Ltd .It gives best quality logistics service ,ie is AFM Logistics Pvt Ltd is an international freight forwarding and customs clearing company established in Delhi. The company was constituted in 2012 and is indulged in providing complete logistics solution. The company has its own setup and wide network of agents throughout the world. International Logistics Companies In India . They are the best air cargo and ocean freight forwarding company in Delhi, India. AFM Logistics Pvt Ltd has been working as Import and Export Agent in India since 2012. They have been providing personal baggage shipping services in India for a very long time.
    9050025388

    ReplyDelete
  47. Thanks for sharing the informative data. Keep sharing…
    Jewellery Software
    Jewellery Software

    ReplyDelete