Android Push Notifications using Google Cloud Messaging (GCM), PHP, MySQL and OKHttp – Square Open Source

In this tutorial we are going to learn how to create android Push Notifications using Google Cloud Messaging (GCM), Php, MySql and OkHttp – Square Open Source library. This will be a long tutorial but if you can following it to the end you will be amazed by the amount of knowledge you will gain.

According to the Google – Google Cloud Messaging (GCM) is a free service that enables developers to send messages between servers and client apps. This includes downstream messages from servers to client apps, and upstream messages from client apps to servers.

For example, a lightweight downstream message could inform a client app that there is new data to be fetched from the server, as in the case of a “new email” notification. For use cases such as instant messaging, a GCM message can transfer up to 4kb of payload to the client app. The GCM service handles all aspects of queueing of messages and delivery to and from the target client app.

Most of the Push Notification using Google Cloud Messaging (GCM) tutorials online are out of date although most still work. This tutorial uses latest Google API.

Check out Android Firebase Cloud Messaging Push Notification example

We will first register with Google API Console to obtain GCM API key and SenderID. After the registration, we will download a .json file that we will put on the app folder of our application.

The client application will need to register with GCM server and obtain a unique token which the GCM server will use to identify the device. Once the token is obtain, the device will send the token to the websever. The web server will send and store the token to MySql database. We will also create a backend form in our server where we will input message that will be push to the client application using GCM server.

Let start by creating a configuration file. We will proceed to the getting started with Google Could Messaging page. Then click on the button to get configuration file. Below is the screen-shot.

Google Cloud Messaging

On the next page, we will fill in our app name and the package name of our application. Finally, we will select a country or region. See the screen-shot below.

Google Cloud Messaging

Now, we will enable our Google Cloud Messaging by click the button on this page. See the screen-shot below.

Google Cloud Messaging

The next page will display your server API key and your SenderID. The screen-shot is as shown below.

Google Cloud Messaging

Finally, download the google-services.json file as shown below.

Google Cloud Messaging

We have finish with our server API key and Sender ID setup, now we will proceed to the server side implementation.

We are going to use a local web server (WAMP). Before we start with our web application, we will first create the database. Click on the WAMP server icon, select the menu phpMyAdmin to setup the database structure.

Create a new database called test or any name you like. Use the test as both username and password for user privileged. We will create a table called user in our database. You can as well use the following code to create your user table.

CREATE TABLE IF NOT EXISTS `user` (
  `gcm_regid` text NOT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `id` int(8) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1;

Server Web Application

First, we will connect our web application to our created database. Create a folder in your www folder of your websever called gcm.

Create a configuration file called config.php. This file will contain the database configuration values and our Server API Key.

config.php

<?php

 define("DB_HOST", " ");
 define("DB_USER", " ");
 define("DB_PASSWORD", " ");
 define("DB_NAME", " ");
 
 define("GOOGLE_API_KEY", " ");

?>

Create a new file called db.php which will include our configuration file and connect to our database.

db.php

<?php
include_once 'config.php';

class DbConnect{	
	
	private $connect;	
	
	public function __construct(){
		
		$this->connect = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
		 
		if (mysqli_connect_errno($this->connect))
		{
			echo "Failed to connect to MySQL: " . mysqli_connect_error();  
		}
	}
	
	public function getDb(){
		
		return $this->connect;
	}
	
}

?>

Next we will create a database.php file with three methods we will use in your application. One method is used to store our Device token to the database while the second one is used to return the token from database.

Database.php

<?php

include_once 'db.php';

 class DatabaseLayer{
		
 	private $tables;
	
	public function __constructor(){
		
		$this->tables = "user";
	}
	
	public function insertUserRegistrationId($registration_id){
		
		if(!$this->getAllRegisteredUsers($registration_id)){
			$com = new DbConnect();	
			$sql = "insert into user (gcm_regid, created_at) values ('$registration_id', NOW())";			
		    mysqli_query($com->getDb(), $sql);
		}
	}
	
	public function getAllRegisteredUsers($registration_id){
		$com = new DbConnect();
		$sql = "Select * from  user where gcm_regid = " + $registration_id;
		$result = mysqli_query($com->getDb(), $sql);
		if(count($result) == 1){
			return true;
		}
		return false;
	}
	
	public function getRegistrationId(){
		
		$com = new DbConnect();
		$sql = "select gcm_regid from user limit 1";
		$result = mysqli_query($com->getDb(), $sql);
		$row = mysqli_fetch_row($result);		
		//print_r($row[0]);
		if(count($row) == 1){
			return $row[0];
		}
		return false;
	}	
}
	
?>

Create a new file called registeruser.php. The registeruser.php will receive the token from the client device and it will save the token to the database.

Registeruser.php

<?php
 
 if(isset($_POST['registrationId'])){
     $registration_id = $_POST['registrationId'];
     include_once 'userregistration.php';	
     $UserRegistrationClass = new UserRegistrationFromDevice();
     $UserRegistrationClass->saveNewRegisteredUser($registration_id);	
  } 

?>

The registeruser.php file includes the userregistration.php file. This file contains a method that is used to save receive token from the client app to database.

Userregistration.php

<?php

include_once 'database.php';
include_once 'sendnotification.php';

class UserRegistrationFromDevice{
	
	public function __constructor(){
		
	}
	
	public function saveNewRegisteredUser($user_registration_id){
						
		$db = new DatabaseLayer();
		$db->insertUserRegistrationId($user_registration_id);
		
		$registatoin_ids = array($user_registration_id);
        $message = array("GCM Push" => "Testing Testing");
		
		$severNotification = new SendNotification();
 
        $severNotification->sendPushNotificationToGCMSever($registatoin_ids, $message);
	}
}

?>

We will create an index.php page in our web server. This page will contain a textarea input element which will be used to post message to GCM server which will relay it to the client application.

Index.php

<!doctype html>
<html class="no-js" lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>GCM Push Notification</title>  
    <!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>-->
    <script language="JavaScript" type="text/javascript" src="jquery-2.2.0.min.js"></script> 
    <script language="JavaScript" type="text/javascript" src="js.js"></script> 
   
    
    <style>
    
    body{
    	background-color: #403f22;
    }
    body #form_wrapper{
    	width:800px;
    	height:400px;
    	margin:200px auto;
    	border: 1px solid #FFCC00;
    	text-align: center;
    }
    #form_wrapper > h1{
    	color:#FFFFFF;
    	text-align:center;
    }
    textarea{
    	border: 2px solid #FFCC00;
		margin-bottom: 10px;			
		text-align: center;
		padding: 10px;
		font-size: 25px;
		font-weight: bold;
	}
	input{
		background-color: #FFCC00;
		border: 5px solid #fff;
		padding: 10px;
		cursor: pointer;
		color: #fff;
		font-weight: bold;
	}
	.submit-button{
		width:96px;
		height: 60px;
		background-color: #FFCC00;
		border: 2px solid #000000;
		margin-top:24px;
		padding:12px;
	}
	</style>
	
	
</head>
<body>
  	
<div id="form_wrapper">
  <h1>GCM Push Notification Backend</h1>
  <?php 
    include_once 'database.php';
	$db = new DatabaseLayer();
	$user_id = $db->getRegistrationId();
  
   ?>	
	<form>	
		<input type="hidden" id="user_id" name="user_id" value="<?php echo $user_id ? $user_id : 0 ?>">			                                                      
		<textarea rows="5" id="message" name="message" cols="45" placeholder="Write push notification message"></textarea> 
		<p><a class="submitbutton submit-button"> Send data to GCM </a></p>
		
		<!--<p><input type="submit"  value="submit" name="submit" id="submitbutton" /></p>-->
	</form>
</div>


</body>
</html>

In the Form section of the page, we call the getRegistrationId() method of DatabaseLayer class to obtain the device id. The obtained device id is added to a hidden input field.

When the submit link button of the Form element is clicked, we will use a Javascript Ajax call to pass the token and the input message to servermessagesending.php file.

Servermessagesending.php

<?php

include_once 'sendnotification.php';

if(isset($_POST['user_id']) && isset($_POST['message'])){
	
	$registration_id = array($_POST['user_id']);
	$message = array("GCM Notice" => $_POST['message']);
	
	$notificationClass = new SendNotification();	
	$notificationClass->sendPushNotificationToGCMSever($registration_id, $message);		
}

?>

Finally, the servermessagesending.php file uses the method sendPushNotificationToGCMServer($registration_id, $message) from the sendnotification.php to send notification.

SendNotification.php

<?php

 class SendNotification{ 	

 	
	public function __construct(){
		
	}
	
	public function sendPushNotificationToGCMSever($registatoin_ids, $message){
		
		include_once 'config.php';
		$path_to_gmc_server = 'https://android.googleapis.com/gcm/send';
		
		$fields = array(
            'registration_ids' => $registatoin_ids,
            'data' => $message,
        );
 
        $headers = array(
            'Authorization: key=' . GOOGLE_API_KEY,
            'Content-Type: application/json'
        );
		
		$ch = curl_init();
 
        curl_setopt($ch, CURLOPT_URL, $path_to_gmc_server);
 
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
 
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
 
        $result = curl_exec($ch);
        if ($result === FALSE) {
            die('Curl failed: ' . curl_error($ch));
        }
 
        curl_close($ch);
        echo $result;		
	}
 }

?>

Remember that I said we used a Javascript Ajax call to pass data from our form to the GCM server.

You can download and use a Jquery library or use the hosted Jquery library link in your index.php file. Create a new Javascript file called js.js. Copy and paste the following code inside the file.

$(document).ready(function(){
	
	$('.submitbutton').on("click",function(){
		
		///get token and validate it 
		var message = $("#message").val();	
		
		if(message == ""){
			alert("Message input field must be filled");			
			return;
		}	
		
		var user_id = $("#user_id").val();
		if(user_id == ""){
			alert("You must register with Google Cloud Messaging before sending message");			
			return;
		}	
		
		$.ajax({
			method: "POST",
            url: "servermessagesending.php",
            data: { message : message, user_id : user_id }
        })
        .done(function( msg ) {
            alert( "Data Saved: " + msg );
         });

		return false;
	});
	
});

We are done the our server application, the next step is to create a new android application called AndroidGoogleCloudMessaging.

In our android application, we will make use of the example code provided by Google for GCM application example. We will modify it to suit what we are planning to achieve.

Before we start, it is important for you to understand the tools and environment I used in this android tutorial. Feel free to use tools you are familiar with.

Windows 7

Android Studio

Sony Xperia ZL

Min SDK 14

Target SDK 23

To create a new android application project, following the steps as stipulated below.

Go to File menu

Click on New menu

Click on Android Application

Enter Project name: AndroidGoogleCloudMessaging

Package: com.inducesmile.androidgooglecloudmessaging

Select Blank Activity

Keep other default selections

Continue to click on next button until Finish button is active, then click on Finish Button.

If you are using Android Studio as your choice IDE, the new project will create a default

MainActivity.java file and its corresponding layout file.

First, we are going to add some of the dependency libraries we are going to use in this application.

In your project build.gradle file, add the following line of code to the classpath dependency.

dependencies {
    classpath 'com.android.tools.build:gradle:1.5.0'
    classpath 'com.google.gms:google-services:1.5.0-beta2'  
}

Open your app build.gradle file and add the following dependencies.

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile "com.google.android.gms:play-services:8.3.0"   
    compile 'com.squareup.okhttp3:okhttp:3.1.2'
}

You can see that we have imported the OkHttp library which we will use to send request to our application web server.

Add the Google Services as a plugin in the application build.gradle file.

apply plugin: 'com.google.gms.google-services'

We are going to manually register our project android service classes in our project AndroidManifest.xml file.

The code for our AndroidManifest.xml file is as shown below.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.inducesmile.androidgooglecloudmessaging">
    <!-- For accessing Internet -->
    <uses-permission android:name="android.permission.INTERNET"/>
    <!-- For checking current network state -->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <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="com.example.gcm" />
            </intent-filter>
        </receiver>
        <service
            android:name="com.inducesmile.androidgooglecloudmessaging.MyGcmListenerService"
            android:exported="false" >
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            </intent-filter>
        </service>
        <service
            android:name="com.inducesmile.androidgooglecloudmessaging.MyInstanceIDListenerService"
            android:exported="false">
            <intent-filter>
                <action android:name="com.google.android.gms.iid.InstanceID" />
            </intent-filter>
        </service>
        <service
            android:name="com.inducesmile.androidgooglecloudmessaging.RegistrationIntentService"
            android:exported="false">
        </service>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Our main layout file uses a TextView to notify us when a notification has been sent to our web server application. We are going to add a TextView and a Button View in our layout file. The code for our layout file is as shown below.

Activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/notificationbg"
    tools:context="com.inducesmile.androidgooglecloudmessaging.MainActivity">
    <Button
        android:id="@+id/register_push"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center|center_horizontal"
        android:textColor="@color/colorWhite"
        android:textStyle="bold"
        android:textSize="16sp"
        android:text="@string/button_name"
        android:layout_centerVertical="true"
        android:background="@color/colorPrimary"
        android:padding="16dp"
        android:layout_centerHorizontal="true"/>
    <TextView
        android:id="@+id/is_register"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/register_push"
        android:layout_centerHorizontal="true"
        android:layout_margin="24dp"
        android:textStyle="bold"
        android:textColor="@color/colorWhite"
        android:text="@string/registration_status" />
</RelativeLayout>

MainActivity.java

The MainActivity.java file will check if our client application has register with the web server and also if the device has a Google Play Services installed in the device.

This class also sends an intent message to the RegisterIntentService.java to send a registration notification to the server.

The code for MainActivity.java is as shown below.

package com.inducesmile.androidgooglecloudmessaging;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
public class MainActivity extends AppCompatActivity {
    private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
    private static final String TAG = "MainActivity";
    private BroadcastReceiver mRegistrationBroadcastReceiver;
    private TextView registrationStatus;
    private Button clickToRegister;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        registrationStatus = (TextView)findViewById(R.id.is_register);
        mRegistrationBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
                boolean sentToken = sharedPreferences.getBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, false);
                if (sentToken) {
                    registrationStatus.setText(getString(R.string.gcm_send_message));
                } else {
                    registrationStatus.setText(getString(R.string.token_error_message));
                }
            }
        };
        clickToRegister = (Button)findViewById(R.id.register_push);
        clickToRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            }
        });
        if (checkPlayServices()) {
            // Start IntentService to register this application with GCM.
            Intent intent = new Intent(this, RegistrationIntentService.class);
            startService(intent);
        }
    }
    @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();
    }
    /**
     * Check the device to make sure it has the Google Play Services APK. If
     * it doesn't, display a dialog that allows users to download the APK from
     * the Google Play Store or enable it in the device's system settings.
     */
    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;
    }
}

The Instance ID listener can be used to reset or refresh the registration token in the server. This can also occur when an app is uninstall from a device. The code snippet for this class is shown below.

MyInstanceIDListenerService.java

package com.inducesmile.androidgooglecloudmessaging;
import android.content.Intent;
import com.google.android.gms.iid.InstanceIDListenerService;
public class MyInstanceIDListenerService extends InstanceIDListenerService {
    @Override
    public void onTokenRefresh() {
        //super.onTokenRefresh();
        // Fetch updated Instance ID token and notify our app's server of any changes (if applicable).
        Intent intent = new Intent(this, RegistrationIntentService.class);
        startService(intent);
    }
}

MyGcmListenerService.java

This is a service class that receives message from the GCM server. It uses the overriden method of the class onMessageReceived(String from, Bundle data) to retrieve the message. The message is then pass to the sendNotification() method of the class. The code is as shown below.

package com.inducesmile.androidgooglecloudmessaging;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import com.google.android.gms.gcm.GcmListenerService;
public class MyGcmListenerService extends GcmListenerService {
    private static final String TAG = "MyGcmListenerService";
    @Override
    public void onMessageReceived(String from, Bundle data) {
        //super.onMessageReceived(from, data);
        String message = data.getString("message");
        Log.d(TAG, "From: " + from);
        Log.d(TAG, "Message: " + message);
        if (from.startsWith("/topics/")) {
            // message received from some topic.
        } else {
            // normal downstream message.
        }
        sendNotification(message);
    }
    private void sendNotification(String message) {
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.notification_icon)
                .setContentTitle("GCM Message Received")
                .setContentText(message)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(0, notificationBuilder.build());
    }
}

RegistrationIntentService.java

We are going to implement the sendRegistrationToServer(String token) method of this class. We are going to use the OkHttp library to send request to our web server. The method implementation is as shown in the complete class code.

package com.inducesmile.androidgooglecloudmessaging;
import android.app.IntentService;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.android.gms.iid.InstanceID;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class RegistrationIntentService extends IntentService {
    private static final String TAG = "RegistrationIntentService";
    private static final String pathToServer = "Path to registeruser.php";
    public RegistrationIntentService() {
        super(TAG);
    }
    @Override
    protected void onHandleIntent(Intent intent) {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        try {
            // Initially this call goes out to the network to retrieve the token, subsequent calls are local.
            // R.string.gcm_defaultSenderId (the Sender ID) is typically derived from google-services.json.
            InstanceID instanceID = InstanceID.getInstance(this);
            String token = instanceID.getToken(getString(R.string.gcm_defaultSenderId), GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
            Log.i(TAG, "GCM Registration Token: " + token);
            sendRegistrationToServer(token);
            // You should store a boolean that indicates whether the generated token has been
            // sent to your server. If the boolean is false, send the token to your server,
            // otherwise your server should have already received the token.
            sharedPreferences.edit().putBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, true).apply();
        } catch (Exception e) {
            Log.d(TAG, "Failed to complete token refresh", e);
            // If an exception happens while fetching the new token or updating our registration data
            // on a third-party server, this ensures that we'll attempt the update at a later time.
            sharedPreferences.edit().putBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, false).apply();
        }
        // Notify UI that registration has completed, so the progress indicator can be hidden.
        Intent registrationComplete = new Intent(QuickstartPreferences.REGISTRATION_COMPLETE);
        LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
    }
    private void sendRegistrationToServer(String token) {
        final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        OkHttpClient client = new OkHttpClient();
        RequestBody body = RequestBody.create(JSON, bowlingJson(token));
        Request request = new Request.Builder()
                .url(pathToServer)
                .post(body)
                .build();
        Response response = null;
        try {
            response = client.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            //Log.d(TAG, "Response");
            Log.d(TAG, "Response" + response.body().string());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private String bowlingJson(String token) {
        return "{'registrationId': " + token + "}";
    }
}

This brings us to the end of this tutorial, If you find anything confusing kindly contact me with your questions or use the comment box below.

Now, when you run your application you will see the interface that looks similar to the sample that was shown earlier on.

You can download the code for this tutorial below. If you are having hard time downloading the tutorials, kindly contact me.

 

 

Remember to subscribe with your email address so that you will be among the first to receive our new post once it is published.

Please if you love this tutorial, kindly download my new android app – Daily Pocket Calculator – in Google Play Store and let me know what you think about it.

OTHER INTERESTING POSTS:

18 Comments

    • Henry
      • Henry
    • Henry
    • Henry
    • Henry

Add a Comment