Send Push Notification to Android Device

Often you may need to write services for a mobile APP. we all know apps throw push notifications, Push notification bring us the important information about the app.
How push notification is sent to user:
STEPS
1. First we fetch the message form the database to our application server. 
2. Send message to google GCM server.
3. Then the GCM server will push those messages when ever the mobile is 
     connected to the internet.
1. We all know how to fetch the data from the database.
2. Sending message to GCM server
a) First we need to add gcm-server dependency to our pom.xml file.
            com.ganyo
            gcm-server
            1.0.2
            jar
  

b) Create a class and copy the below code. 
import com.google.android.gcm.server.Message;
import com.google.android.gcm.server.Result;
import com.google.android.gcm.server.Sender;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class SendPushNotification {
    // google server will profde this key , 
    //when our app register for the push notification
    private static final String GOOGLE_SERVER_KEY
                                                                    = “AIzaSyDDuLlpT4xH”;
    // the registration id, that is unique for the each android device
    private static final String regId = “APA91bHmjeWYjOROcG6oEt”;
    public static void main(String[] args) {
        try {
            // message that we need to send 
            String userMessage = “message”;
            // Register the sender
            Sender sender = new Sender(GOOGLE_SERVER_KEY);
            // prepate the message
            Message message = new Message.Builder().timeToLive(30)
                .delayWhileIdle(true).addData(“message”, userMessage).build();
            // send the message to the GCM server.
            Result result = sender.send(message, regId, 1);
            System.out.println(“push status ” + result.toString());
        } catch (IOException ex) {
            Logger.getLogger(SendPushNotification.class.getName())
                    .log(Level.SEVERE, null, ex);
        }
    }
}

3. There you go, you have successfully submitted    the push message to the GCM server. Next time your app client connect to the internet  you message will be delivered by the GCM server.
Advertisements

About sivateja

I am a professional graduate..I am passionate about Latest Technology.
This entry was posted in Android, push notification. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s