Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Push Notification using GCM in Android

    • 0
    • 2
    • 0
    • 2
    • 0
    • 0
    • 0
    • 0
    • 677
    Comment on it

    For Push Notification using GCM in Android, use the following steps:

    1. Create the Google Api Project on Google Console.

    2. Note down the project number which will be used as GCM Sender Id.

    3. Enable the GCM service by turn on the toggle for Google Cloud Messaging for Android on the displayer list that will display after clicking on "APIs & auth" on the side bar on left.

    4. Get the API key by registering the App. And after registering app copy API key which will be used for Authentication on Server side.

    5. Put gcm.jar into your libs folder of the project.

    6. Install the Google Play Services if not installed. you can install it from Window sdk Manager > Extras > Google Play services.

      Then copy the project from C:\android-sdk-windows\extras\google\google_play_services\libproject\google-play-services_lib into the location where your Application project is maintained.

      Import the project into your workspace by clicking Import > Existing Android Code into Workspace

    1. Write the following required permissions into your AndroidManifest.xml:
    <uses-permission android:name="android.permission.INTERNET" />
    <!-- This app has permission to register with GCM and receive message -->
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    <!-- GCM connects to Google Services. -->
    <uses-permission android:name="android.permission.INTERNET" />
    <!-- GCM requires a Google account. -->
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <!-- Keeps the processor from sleeping when a message is received. -->
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <permission
    <!-- com.textshare.android is my package name, you will use your application package name in this -->
    android:name="com.textshare.android.permission.C2D_MESSAGE"
    android:protectionLevel="signature" />
    
    1. Write the following code inside the application tag into your AndroidManifest.xml:

    <receiver android:name="com.google.android.gcm.GCMBroadcastReceiver" 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"/>
    
     <!-- com.textshare.android is my package name, you will use your application package name in this -->
           <category android:name="com.textshare.android" />
            </intent-filter>
        </receiver>
    
        <!-- com.textshare.android is my package name, you will use your application package name in this -->
        <service android:name="com.textshare.android.GCMIntentService" />
    
    1. Write class GCMIntentService.java inside your package
    package com.textshare.android;
    
    import org.json.JSONException;
    import org.json.JSONObject;
    
    import android.app.Notification;
    import android.app.NotificationManager;
    import android.app.PendingIntent;
    import android.content.Context;
    import android.content.Intent;
    import android.os.AsyncTask;
    
    import com.google.android.gcm.GCMBaseIntentService;
    import com.textshare.android.util.MyUtility;
    import com.textshare.android.util.ServerUrl;
    import com.textshare.android.util.WebServiceConnection;
    
    public class GCMIntentService extends GCMBaseIntentService
    {
        GCMIntentService gcnIntentService;
        public GCMIntentService()
        {
            //Your-Sender-ID is the project number you got from the API Console
            super("Your-Sender-ID");
            gcnIntentService=this;
        }
    
        @Override
        protected void onError(Context arg0, String arg1) {
    
        }
    
        @SuppressWarnings("deprecation")
        @Override
        protected void onMessage(Context arg0, Intent intent) {
    
            final String payload = intent.getStringExtra("message");
    
            NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
            Notification notification = new Notification(R.drawable.app_logo,intent.getStringExtra("message"), System.currentTimeMillis());
    
            // Hide the notification after its selected
            notification.flags |= Notification.FLAG_AUTO_CANCEL;
            notification.defaults |= Notification.DEFAULT_SOUND;
    
            // After clickin on notification it will open the activity that will be defined here
            Intent intents = new Intent(this, LandingScreen.class);
            intents.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,intents, Intent.FLAG_ACTIVITY_NEW_TASK);
    
            notification.setLatestEventInfo(this,"TextShare Alert",intent.getStringExtra("message"), pendingIntent);
            notificationManager.notify(0, notification);
        }
        @Override
        protected void onRegistered(Context arg0, String registration) 
        {
            // save AppId in shared preferences for further use
            MyUtility.saveDeviceAppId(gcnIntentService, registration);
    
            // Send Registered Id into server for receiving Push Notification
            SyncAppId syncID=new SyncAppId();
            syncID.execute(registration);
        }
    
        @Override
        protected void onUnregistered(Context arg0, String arg1) {
            ServerUrl.sendLog("UnRegistered : "+arg1);
        }
    
    
        /**
         * This represents a asynchronous task used to  
         * sync Device Application id from server
         *
         */
        class SyncAppId extends AsyncTask {
            @Override
            protected String doInBackground(String... urls) 
            {       
                try
                {
                    JSONObject data=new JSONObject();
                    data.put("deivceToken",urls[0]);
    
                    // Hit the API to store RegisterdId on server
                    String response=WebServiceConnection.getData(data.toString(),ServerUrl.BASE_SERVER_URL+ServerUrl.REGISTER_APP_ID);
                    ServerUrl.sendLog(response);
    
                    return response;
                }
                catch(JSONException e)
                {
                    e.printStackTrace();
                    return null;
                }
            }
            @Override
            protected void onPostExecute(String result) 
            {
                ServerUrl.sendLog("Results : "+result);
            }
        }
    }
    1. GCM registration: Write the following code in onCreate() methos of your LandingScreen, so that when you launch your app it will check for GCM registration:
    try
            {
                GCMRegistrar.checkDevice(this);
                GCMRegistrar.checkManifest(this);
                final String regId = GCMRegistrar.getRegistrationId(this);
                if (regId.equals("")) 
                {
    
                    //Your-Sender-ID is the project number you got from the API Console
                    GCMRegistrar.register(this, "Your-Sender-ID");
                }
                else 
                {
                    // If GCM is already registered then send the regId into Server
                    SyncAppId syncID=new SyncAppId();
                    syncID.execute(regId);
                }
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }

    Hope this will help you.Please share the experiences you had while implementing Push Notification in Android as this will help other people who read the post.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: