Register for GCM registration id in android application and receive and show notification

So after learning GCM process flow and how to create a project on Google Developer Console now its time to learn how to register device and android app on GCM and get registration id. This registration id is then used to send notification message on GCM server and GCM server delivers this message to our android device.

So first thing we need to do is install Google Play Services using Android SDK Manager. You can find Google Play Services under Extras heading in android SDK manager.

Setup Google Play Service

After installing google play service we have to follow below steps to start using google play services in our project

  1. Import google-play-services_lib project from C:Program Files (x86)Androidandroid-sdkextrasgooglegoogle_play_serviceslibproject (or C:Program FilesAndroidandroid-sdkextrasgooglegoogle_play_serviceslibproject) to your work space.
  2. Right click on your project in package explorer of Eclipse IDE and go toProperties -> Android -> Library -> Add. Now select google-play-services_lib project and click ok.Again click ok to close project properties. Now we are ready to start coding.

Implement Google Play Service

Now we are ready to start implementing notification service in Android application
  1. Add import statement for com.google.android.gms.common.ConnectionResult and com.google.android.gms.common.GoogleApiAvailability in your MainActivity.java
    import com.google.android.gms.common.ConnectionResult; 
    import com.google.android.gms.common.GoogleApiAvailability;

     

  2. Add a TextView and a ProgressBar in your activity layout
    <TextView android:text="@string/registering_message" android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/informationTextView"
    android:textAppearance="?android:attr/textAppearanceMedium" />
    <ProgressBar
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/registrationProgressBar" />

     

  3. Add below object declaration in your MainActivity
    private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
    private BroadcastReceiver mRegistrationBroadcastReceiver;
    private ProgressBar mRegistrationProgressBar;
    private TextView mInformationTextView;

     

  4. Initialize BroadcastReceiver object and override OnReceive action. Use below code in your OnCreate method of MainActivity to do so
          mRegistrationProgressBar = (ProgressBar) findViewById(R.id.registrationProgressBar);
    mRegistrationBroadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
    mRegistrationProgressBar.setVisibility(ProgressBar.GONE);
    SharedPreferences sharedPreferences =                       PreferenceManager.getDefaultSharedPreferences(context);
    boolean sentToken = sharedPreferences                      .getBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, false);
    if (sentToken) {
    mInformationTextView.setText(getString(R.string.gcm_send_message));
    } else {
    mInformationTextView.setText(getString(R.string.token_error_message));
    }
    }
    };
    
    mInformationTextView = (TextView) findViewById(R.id.informationTextView);
  5. Override two methods (onResult and OnPause) and define one more method (checkPlayService).
    @Override
    protected void onResume() {
           super.onResume();
          
     LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver, new IntentFilter(QuickstartPreferences.REGISTRATION_COMPLETE));
       }
    @Override
    protected void onPause() {
    
    LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver);
    super.onPause();
    }
    
    private boolean checkPlayServices() {
    GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
    int resultCode = apiAvailability.isGooglePlayServicesAvailable(this);
    if (resultCode != ConnectionResult.SUCCESS) {
    if (apiAvailability.isUserResolvableError(resultCode)) {
    apiAvailability.getErrorDialog(this, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST).show();
    }
    else {
    Log.i(TAG, "This device is not supported.");
    finish();
    }
    return false;
    }
    return true;
    }

     

  6. We are done with the MainActivity and layout. Now we need to add four classes in our application package- MyGcmListenerService extended from GcmListenerService – Download
    – MyInstanceIDListenerService extended from InstanceIDListenerService – Download
    – QuickstartPreferences for static final string to use with SharedPreferences – Download
    – RegistrationIntentService extended from IntentService – Download
  7. Update AndroidManifest.xmlAdd Permission
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.INTERNET" />

    Add meta data tag. This is very important

    <meta-data android:name="com.google.android.gms.version"  android:value="@integer/google_play_services_version" />

    Add receiver and services

    <!-- [START gcm_receiver] -->
            <receiver
                android:name="com.google.android.gms.gcm.GcmReceiver"
                android:exported="true"
                android:permission="com.google.android.c2dm.permission.SEND" >
                <intent-filter>
                    <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                    <category android:name="gcm.play.android.samples.com.gcmquickstart" />
                </intent-filter>
            </receiver>
            <!-- [END gcm_receiver] -->
    <!-- [START gcm_listener] -->
    <service
    android:name="com.example.myfirstapp.MyGcmListenerService"
    android:exported="false" >
    <intent-filter>
    <action android:name="com.google.android.c2dm.intent.RECEIVE" />
    </intent-filter>
    </service>
    <!-- [END gcm_listener] -->
    <!-- [START instanceId_listener] -->
    <service
    android:name="com.example.myfirstapp.MyInstanceIDListenerService"
    android:exported="false">
    <intent-filter>
    <action android:name="com.google.android.gms.iid.InstanceID"/>
    </intent-filter>
    </service>
    <!-- [END instanceId_listener] -->
    <service
    android:name="com.example.myfirstapp.RegistrationIntentService"
    android:exported="false">
    </service>
Now we are done with all needed code and configuration. Just run app on device and get the registration id in logs.

Leave a Reply

Your email address will not be published.