Simplified Coding

  • About
  • Contact Us
  • Advertise
  • Privacy Policy
You are here: Home / Android Application Development / Android Advance / Google Cloud Messaging Tutorial for Android Application

Google Cloud Messaging Tutorial for Android Application

April 21, 2016 by Belal Khan 68 Comments

Hello friends, so I am back with one more Google Cloud Messaging Tutorial. In the last Google Cloud Messaging Tutorial we seen how we can implement push notifications using gcm to our android application. You can follow the last tutorial from below. In this tutorial we will see how you can send push notification to multiple android device using gcm.

Android Push Notification using GCM Tutorial

It is really important that you go through the above mentioned gcm tutorial first before moving ahead on this post.

Contents

  • 1 Google Cloud Messaging Tutorial to Broadcast a Message Across Multiple Devices
    • 1.1 Live Demo of The App
  • 2 Creating Server Side Scripts and Database
    • 2.1 Creating Database
    • 2.2 Creating REST API
    • 2.3 REST API Details
    • 2.4 Creating Web Panel to Send Push Notification
  • 3 Creating Android Application Project
    • 3.1 Creating classes for GCM
    • 3.2 Creating the Helper Classes
    • 3.3 Creating the Activities
    • 3.4 Adding Permission, Services and Receiver to AndroidManifest.xml
    • 3.5 Sharing is Caring:
    • 3.6 Related

Google Cloud Messaging Tutorial to Broadcast a Message Across Multiple Devices

Before moving ahead to the tutorial you can check this video to know what we will be creating.

In this post we will store the registration token to our server. For this I will be using MySQL and PHP as my server side platform.

And for the networking operations I will be using Volley Library.

Before starting the tutorial I am assuming that you have already implemented gcm into your app. If you haven’t done it yet you can go through this Android Push Notification Tutorial to implement it into your app.

Live Demo of The App

You can see the live demo of this Google Cloud Messaging Tutorial from the link given below.

Google Cloud Messaging Tutorial Live Demo

Creating Server Side Scripts and Database

This time we will store the data to our server. For this I am using WAMP server, you can also use other servers like xampp, lamp etc.

For the server side part we will create REST API using PHP SLIM Framework. I have already covered a REST API Tutorial so in this post I will not be explaining much.  So lets begin.

Creating Database

  • First we need the database. So go to your phpMyAdmin and create the following database.

database

Creating REST API

  • Now open PHP Storm (Or any other IDE which you use for PHP Development) and create a new project. I created a project named PushNotification.

directory structure

  • As you can see many files in the project directory.
    The folder include contains 3 files Config.php, DbConnect.php and DbOperation.php. If you want explanations for these files please do check the Rest API Tutorial using PHP Slim Framework.
    The folder libs contain the SLIM Framework library files. You can download slim framework from here. Download SLIM Framework and paste it inside your libs folder.
    The folder v1 containing .htaccess for URL rules and index.php for handling all the API calls.
    Then comes index.php this is the web panel to send the push notification.
    send.php and sendGCM.php is containing the codes that will help in sending push notification.
    Other than these files we have jquery file and style.css to for UI design.
  • You have to create your project directory as the same I shown in the above screenshot. Now I will give you the codes for all of these files.
  • First create Config.php inside include folder and write the following code. You need to put your database details here.

PHP
1
2
3
4
5
<?php
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');
define('DB_NAME', 'db_pushnotification');

  •  Now create DbConnect.php this file will be used to connect to the database.

DbConnect.php
PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<?php
 
class DbConnect
{
    private $conn;
 
    function __construct()
    {
    }
 
    /**
     * Establishing database connection
     * @return database connection handler
     */
    function connect()
    {
        require_once 'Config.php';
 
        // Connecting to mysql database
        $this->conn = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
 
        // Check for database connection error
        if (mysqli_connect_errno()) {
            echo "Failed to connect to MySQL: " . mysqli_connect_error();
        }
 
        // returing connection resource
        return $this->conn;
    }
}

  • Create DbOperation.php. This file will handle all the database related operations.

DbOperation.php
PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
<?php
 
class DbOperation
{
    private $conn;
 
    function __construct()
    {
        require_once dirname(__FILE__) . '/Config.php';
        require_once dirname(__FILE__) . '/DbConnect.php';
        // opening db connection
        $db = new DbConnect();
        $this->conn = $db->connect();
    }
    
    //Adding a user to database
    public function addUser($name, $email)
    {
        if (!$this->isUserExists($email)) {
            $stmt = $this->conn->prepare("INSERT INTO users(name,email) values(?, ?)");
            $stmt->bind_param("ss", $name, $email);
            $result = $stmt->execute();
            $stmt->close();
            if ($result) {
                return 0;
            } else {
                return 1;
            }
        } else {
            return 2;
        }
    }
 
    //Getting the user id
    public function getUserId(){
        $stmt = $this->conn->prepare("SELECT MAX(id) as id FROM users");
        $stmt->execute();
        $result = $stmt->get_result();
        $id = $result->fetch_assoc();
        return $id['id'];
    }
 
    //Adding gcm registration token to the user
    public function addRegistrationToekn($id,$token){
        $stmt = $this->conn->prepare("UPDATE users SET token=? WHERE id=?");
        $stmt->bind_param("si",$token,$id);
        $result = $stmt->execute();
        $stmt->close();
        if($result){
            return true;
        }
        return false;
    }
 
    //checkin if user already exist
    private function isUserExists($email)
    {
        $stmt = $this->conn->prepare("SELECT id from users WHERE email = ?");
        $stmt->bind_param("s", $email);
        $stmt->execute();
        $stmt->store_result();
        $num_rows = $stmt->num_rows;
        $stmt->close();
        return $num_rows > 0;
    }
 
    //Getting all user
    public function getAllUsers(){
        $stmt = $this->conn->prepare("SELECT email FROM users");
        $stmt->execute();
        $result = $stmt->get_result();
        return $result;
    }
 
    //Getting individual token for sending message to individual device
    public function getIndividualToken($email){
        $stmt = $this->conn->prepare("SELECT token FROM users WHERE email=?");
        $stmt->bind_param("s",$email);
        $stmt->execute();
        $result = $stmt->get_result();
        $stmt->close();
        $token = $result->fetch_assoc();
        return $token['token'];
    }
 
    //Getting all tokens for broadcasting a message
    public function getAllToken(){
        $stmt = $this->conn->prepare("SELECT token FROM users");
        $stmt->execute();
        $result = $stmt->get_result();
        $stmt->close();
        return $result;
    }
}

  • Now come inside v1 folder and create .htaccess and write the following.

1
2
3
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ %{ENV:BASE}index.php [QSA,L]

  • Now to handle API calls create file index.php and write the following code.

index.php
PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
<?php
require_once '../include/DbOperation.php';
require '.././libs/Slim/Slim.php';
 
\Slim\Slim::registerAutoloader();
 
$app = new \Slim\Slim();
 
 
/* To add user to database
* URL: /adduser
* parameters: name, email
* method: post
* */
$app->post('/adduser', function () use ($app) {
    verifyRequiredParams(array('name','email'));
    $response = array();
    $name = $app->request->post('name');
    $email = $app->request->post('email');
 
    validateEmail($email);
 
    $db = new DbOperation();
    $res = $db->addUser($name, $email);
 
    if ($res == 0) {
        $response["error"] = false;
        $response["id"] = $db->getUserId();
        $response["message"] = "You are successfully registered";
        echoResponse(201, $response);
    } else if ($res == 1) {
        $response["error"] = true;
        $response["message"] = "Oops! An error occurred while registereing";
        echoResponse(200, $response);
    } else if ($res == 2) {
        $response["error"] = true;
        $response["message"] = "Sorry, this email already existed";
        echoResponse(200, $response);
    }
});
 
 
/* To add registration token to a user
* URL: /adduser
* parameters: name, email
* method: put
* */
$app->put('/addtoken/:id','authenticate', function ($id) use ($app) {
    verifyRequiredParams(array('token'));
 
    $token = $app->request()->put('token');
 
    $response = array();
    $db = new DbOperation();
 
    if($db->addRegistrationToekn($id,$token)){
        $response['error'] = false;
        $response['message'] = "Token added successfully";
    }else{
        $response['error'] = true;
        $response['message'] = "Could not add token";
    }
    echoResponse(200, $response);
});
 
function validateEmail($email)
{
    $app = \Slim\Slim::getInstance();
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $response["error"] = true;
        $response["message"] = 'Email address is not valid';
        echoResponse(400, $response);
        $app->stop();
    }
}
 
function echoResponse($status_code, $response)
{
    $app = \Slim\Slim::getInstance();
    // Http response code
    $app->status($status_code);
    // setting response content type to json
    $app->contentType('application/json');
    echo json_encode($response);
}
 
 
function verifyRequiredParams($required_fields)
{
    $error = false;
    $error_fields = "";
    $request_params = array();
    $request_params = $_REQUEST;
    // Handling PUT request params
    if ($_SERVER['REQUEST_METHOD'] == 'PUT') {
        $app = \Slim\Slim::getInstance();
        parse_str($app->request()->getBody(), $request_params);
    }
    foreach ($required_fields as $field) {
        if (!isset($request_params[$field]) || strlen(trim($request_params[$field])) <= 0) {
            $error = true;
            $error_fields .= $field . ', ';
        }
    }
 
    if ($error) {
        // Required field(s) are missing or empty
        // echo error json and stop the app
        $response = array();
        $app = \Slim\Slim::getInstance();
        $response["error"] = true;
        $response["message"] = 'Required field(s) ' . substr($error_fields, 0, -2) . ' is missing or empty';
        echoResponse(400, $response);
        $app->stop();
    }
}
 
function authenticate(\Slim\Route $route)
{
    //Implement authentication here
}
 
 
$app->run();

  • Our API is ready.

REST API Details

  • I have made the API live. So if you don’t want to create your own API you can use mine. The details are below.
URL Method Parameters
http://internetfaqs.net/sc/PushNotification/v1/adduser POST name, email
http://internetfaqs.net/sc/PushNotification/v1/addtoken/:id PUT token
  • Now we need a web interface to send notifications.

Creating Web Panel to Send Push Notification

  • First we will code the script to send push notification. So create a file named sendGCM.php and write the following code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<?php
//Define your GCM server key here
define('API_ACCESS_KEY', 'your server api key');
 
//Function to send push notification to all
function sendToAll($message)
{
    $db = new DbOperation();
    $tokens = $db->getAllToken();
    $regTokens = array();
    while($row = $tokens->fetch_assoc()){
        array_push($regTokens,$row['token']);
    }
    sendNotification($regTokens,$message);
}
 
 
//function to send push notification to an individual
function sendToOne($email,$message){
    $db = new DbOperation();
    $token = $db->getIndividualToken($email);
    sendNotification(array($token),$message);
}
 
 
//This function will actually send the notification
function sendNotification($registrationIds, $message)
{
    $msg = array
    (
        'message' => $message,
        'title' => 'Android Push Notification using Google Cloud Messaging',
        'subtitle' => 'www.simplifiedcoding.net',
        'tickerText' => 'Ticker text here...Ticker text here...Ticker text here',
        'vibrate' => 1,
        'sound' => 1,
        'largeIcon' => 'large_icon',
        'smallIcon' => 'small_icon'
    );
 
    $fields = array
    (
        'registration_ids' => $registrationIds,
        'data' => $msg
    );
 
    $headers = array
    (
        'Authorization: key=' . API_ACCESS_KEY,
        'Content-Type: application/json'
    );
 
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://android.googleapis.com/gcm/send');
    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);
    curl_close($ch);
 
    $res = json_decode($result);
 
    $flag = $res->success;
    if($flag >= 1){
        header('Location: index.php?success');
    }else{
        header('Location: index.php?failure');
    }
}

  • Create index.php and write the following code.

index.php
XHTML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
<!DOCTYPE html>
<html>
<head>
    <title>Android Push Notification using Google Cloud Messaging</title>
    <script src="jquery-1.12.3.min.js"></script>
</head>
<body>
<?php
require_once 'include/DbOperation.php';
?>
 
<header>
    <h1>Android Push Notification using Google Cloud Messaging</h1>
</header>
<div class="body">
    <div class="sendnotification">
        <div class="form">
            <h2>Send Notification</h2>
            <form action="send.php" method="post">
                <div>
                    <input type="radio" name='send' value="all" required/>Send to All
                    <input type="radio" name='send' value="one" required/>Send to Individual
                    <br/>
 
                    <select name="email" class="email" disabled>
                        <?php
                        $db = new DbOperation();
                        $users = $db->getAllUsers();
                        while ($row = $users->fetch_assoc()) {
                            ?>
                            <option value="<?php echo $row['email']; ?>"><?php echo $row['email']; ?></option>
                            <?php
                        }
                        ?>
                    </select><br /><br />
 
 
                    <textarea name="message" placeholder="enter a message" required></textarea><br /><br />
 
 
                    <button>Send Message</button>
                </div>
            </form>
            <div class="result">
                <?php
                if (isset($_REQUEST['success'])) {
                    echo "<strong>Great! </strong> Message sent successfully";
                }
                if (isset($_REQUEST['failure'])) {
                    echo "<strong>Oops! </strong> Some error occurred please try again";
                }
                ?>
            </div>
        </div>
    </div>
</div>
 
<script>
    $("input[name='send']").change(function () {
        if ($(this).val() == "one") {
            $(".email").prop('disabled', false);
        } else {
            $(".email").prop('disabled', 'disabled');
        }
    });
 
</script>
<footer>
    <p>Copyright 2016 &copy All Rights are Reserved to <a href="https://www.simplifiedcoding.net">Simplified Coding</a>
    </p>
</footer>
</body>
</html>

  • As you can see in the above code we have a form with method post. And in action we have written send.php that will handle the request. So create a file named send.php and write the following code.

send.php
PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<?php
 
//Including required files
require_once 'include/DbOperation.php';
require_once 'sendGCM.php';
 
 
//Checking the request
if($_SERVER['REQUEST_METHOD']=='POST'){
    //Getting message to send
    $message = $_POST['message'];
    
    //Getting the option i.e. whether the user selected send to all or send to individual
    $send = $_POST['send'];
    
    //If send to all is selected
    if($send == "all"){
        //Calling the function send to all
        sendToAll($message);
    }else{
        //else calling sendtoone
        $email = $_POST['email'];
        sendToOne($email,$message);
    }
 
}else{
    header('Location: index.php');
}

  • Thats all for the server side part. Now we will move to creating the android application for this Google Cloud Messaging Tutorial.

Creating Android Application Project

  • Open Android Studio and create a new project. I created GCMPushNotification.  I am assuming that you have already added google-services.json to your project by configuring your your google app in google’s developer console. I am also assuming that you have configured the gradle files the same as we did in the last tutorial.
  • You also need to add volley to your project. You can add volley by adding the following line in the dependencies block of your app level build.gradle file

1
    compile 'com.android.volley:volley:1.0.0'

Creating classes for GCM

  • Now you have to create GCMRegistrationIntentService.java,  GCMTokenRefreshListenerService.java and GCMPushReceiverService.java the same as we created in the last tutorial.
  • GCMRegistrationIntentService.java 

GCMRegistrationIntentService
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package net.simplifiedcoding.gcmpushnotification;
 
import android.app.IntentService;
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
 
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.android.gms.iid.InstanceID;
 
import java.util.HashMap;
import java.util.Map;
 
 
/**
* Created by Belal on 4/15/2016.
*/
public class GCMRegistrationIntentService extends IntentService {
    public static final String REGISTRATION_SUCCESS = "RegistrationSuccess";
    public static final String REGISTRATION_ERROR = "RegistrationError";
    public static final String REGISTRATION_TOKEN_SENT = "RegistrationTokenSent";
 
    public GCMRegistrationIntentService() {
        super("");
    }
 
 
    @Override
    protected void onHandleIntent(Intent intent) {
        registerGCM();
    }
 
    private void registerGCM() {
        Intent registrationComplete = null;
        String token = null;
        try {
            InstanceID instanceID = InstanceID.getInstance(getApplicationContext());
            token = instanceID.getToken(getString(R.string.gcm_defaultSenderId), GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
            Log.w("GCMRegIntentService", "token:" + token);
 
            sendRegistrationTokenToServer(token);
            registrationComplete = new Intent(REGISTRATION_SUCCESS);
            registrationComplete.putExtra("token", token);
        } catch (Exception e) {
            Log.w("GCMRegIntentService", "Registration error");
            registrationComplete = new Intent(REGISTRATION_ERROR);
        }
        LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
    }
 
    private void sendRegistrationTokenToServer(final String token) {
 
        final int id = MyApplication.getInstance().getSharedPrefManager().getUserId();
 
        StringRequest stringRequest = new StringRequest(Request.Method.PUT, Constants.URL_REGISTRATION_TOKEN + id,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        Intent registrationComplete = new Intent(REGISTRATION_TOKEN_SENT);
                        LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(registrationComplete);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
 
                    }
                }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                params.put("token", token);
                return params;
            }
        };
 
        MyApplication.getInstance().addToRequestQueue(stringRequest);
    }
}

  • GCMTokenRefreshListenerService.java

GCMTokenRefreshListenerService.java
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package net.simplifiedcoding.gcmpushnotification;
import android.content.Intent;
 
import com.google.android.gms.iid.InstanceIDListenerService;
 
 
/**
* Created by Belal on 4/15/2016.
*/
public class GCMTokenRefreshListenerService extends InstanceIDListenerService {
 
    @Override
    public void onTokenRefresh() {
        Intent intent = new Intent(this, GCMRegistrationIntentService.class);
        startService(intent);
    }
}

  •  GCMPushReceiverService.java

GCMPushReceiverService.java
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package net.simplifiedcoding.gcmpushnotification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
 
import com.google.android.gms.gcm.GcmListenerService;
 
 
/**
* Created by Belal on 4/15/2016.
*/
 
public class GCMPushReceiverService extends GcmListenerService {
    @Override
    public void onMessageReceived(String from, Bundle data) {
        String message = data.getString("message");
        String title = data.getString("title");
        sendNotification(message, title);
    }
 
    private void sendNotification(String message, String title) {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setSmallIcon(R.mipmap.ic_launcher);
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.simplifiedcoding.net"));
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
        builder.setContentIntent(pendingIntent);
        builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
        builder.setContentTitle(title);
        builder.setContentText(message);
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        notificationManager.notify(1, builder.build());
    }
}

Creating the Helper Classes

  • First we will create a class named Constants.java to store all the important constants.

Constants.java
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package net.simplifiedcoding.gcmpushnotification;
 
/**
* Created by Belal on 4/20/2016.
*/
public class Constants {
    
    private static final String ROOT_URL = "http://192.168.94.1/PushNotification/v1/";
 
    public static final String URL_ADD_USER = ROOT_URL + "adduser";
    public static final String URL_REGISTRATION_TOKEN = ROOT_URL + "addtoken/";
 
    public static final String SHARED_PREF = "gcmpushnotification";
    public static final String KEY_IS_USER_ADDED = "isuseradded";
    public static final String KEY_USER_EMAIL = "useremail";
    public static final String KEY_USER_NAME = "username";
}

  • Now we will create a Singleton class MyApplication.java to handle the requests. Create a class MyApplication.java and write the following code. We have to add this class to the Manifest so be careful while modifying the manifest file at the end of this post.

MyApplication.java
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package net.simplifiedcoding.gcmpushnotification;
 
import android.app.Application;
 
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
 
/**
* Created by Belal on 4/20/2016.
*/
 
public class MyApplication extends Application {
    private RequestQueue mRequestQueue;
    private static MyApplication mInstance;
    private SharedPrefManager sharedPrefManager;
 
    
    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
    }
 
    public SharedPrefManager getSharedPrefManager() {
        if (sharedPrefManager == null)
            sharedPrefManager = new SharedPrefManager(this);
        return sharedPrefManager;
    }
 
    public static synchronized MyApplication getInstance() {
        return mInstance;
    }
 
    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }
        return mRequestQueue;
    }
 
    public <T> void addToRequestQueue(Request<T> req) {
        getRequestQueue().add(req);
    }
 
    public void cancelPendingRequests(Object tag) {
        if (mRequestQueue != null) {
            mRequestQueue.cancelAll(tag);
        }
    }
}

  • Now create one more class named SharedPrefManager.java. This class will handle all the shared preferences functions.

SharedPrefManager.java
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package net.simplifiedcoding.gcmpushnotification;
 
import android.content.Context;
import android.content.SharedPreferences;
 
/**
* Created by Belal on 4/20/2016.
*/
public class SharedPrefManager {
 
    private Context context;
    private SharedPreferences sharedPreferences;
    private SharedPreferences.Editor editor;
 
    private static final String SHARED_PREF = "gcmpushnotification";
    private static final String KEY_IS_USER_ADDED = "isuseradded";
    private static final String KEY_USER_EMAIL = "useremail";
    private static final String KEY_USER_NAME = "username";
    private static final String KEY_USER_ID= "userid";
 
    public SharedPrefManager(Context context){
        this.context = context;
        sharedPreferences = context.getSharedPreferences(SHARED_PREF,Context.MODE_PRIVATE);
        editor = sharedPreferences.edit();
    }
 
    public boolean addUser(int id, String name, String email){
        editor.putInt(KEY_USER_ID,id);
        editor.putString(KEY_USER_EMAIL,email);
        editor.putString(KEY_USER_NAME,name);
        editor.putBoolean(KEY_IS_USER_ADDED,true);
        editor.apply();
        return true;
    }
 
 
    public int getUserId(){
        return sharedPreferences.getInt(KEY_USER_ID, 1);
    }
 
    public String getUserName(){
        return sharedPreferences.getString(KEY_USER_NAME,"");
    }
 
    public String getUserEmail(){
        return sharedPreferences.getString(KEY_USER_EMAIL,"");
    }
 
    public boolean isUserAdded(){
        return sharedPreferences.getBoolean(KEY_IS_USER_ADDED, false);
    }
}

Creating the Activities

  • The first activity which is MainActivity.java is created by default. So come to the layout file of this activity activity_main.xml. And write the following xml code.

activity_main.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<?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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="net.simplifiedcoding.gcmpushnotification.MainActivity">
 
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true">
 
        <TextView
            android:text="Enter Your Name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
 
        <EditText
            android:id="@+id/editTextName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
 
 
        <TextView
            android:text="Enter Your Email"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
 
        <EditText
            android:id="@+id/editTextEmail"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
 
        <Button
            android:text="Receive Notification"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/button" />
    </LinearLayout>
 
</RelativeLayout>

  • The above code will generate the the following output.
google cloud messaging tutorial

google cloud messaging tutorial

  • When the user will tap on the RECEIVE NOTIFICATION  button user will be added to our database. So to add this functionality lets come into MainActivity.java and write the following code.

MainActivity.java
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package net.simplifiedcoding.gcmpushnotification;
 
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
 
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
 
import org.json.JSONException;
import org.json.JSONObject;
 
import java.util.HashMap;
import java.util.Map;
 
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
 
    
    private EditText editTextName;
    private EditText editTextEmail;
    private Button button;
    private ProgressDialog loading;
    private SharedPrefManager sharedPrefManager;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        editTextName = (EditText) findViewById(R.id.editTextName);
        editTextEmail = (EditText) findViewById(R.id.editTextEmail);
        button = (Button) findViewById(R.id.button);
 
        loading = new ProgressDialog(this);
 
        sharedPrefManager = new SharedPrefManager(this);
 
        if(sharedPrefManager.isUserAdded()){
            startActivity(new Intent(this, UserActivity.class));
            finish();
        }
        button.setOnClickListener(this);
    }
 
    private void addUser() {
 
        loading.setMessage("Please wait...");
 
        final String name = editTextName.getText().toString().trim();
        final String email = editTextEmail.getText().toString().trim();
 
        loading.show();
 
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constants.URL_ADD_USER,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        loading.dismiss();
                        try {
                            JSONObject obj = new JSONObject(s);
                            if (!obj.getBoolean("error")) {
                                int id = obj.getInt("id");
                                sharedPrefManager.addUser(id, name, email);
                                //Starting new activity on success
                                startActivity(new Intent(MainActivity.this, UserActivity.class));
                            }else{
                                Toast.makeText(MainActivity.this, "Oops! Some error occured", Toast.LENGTH_LONG).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        Toast.makeText(MainActivity.this, volleyError.getMessage(), Toast.LENGTH_LONG).show();
                    }
                }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                params.put("email", email);
                params.put("name", name);
                return params;
            }
        };
        MyApplication.getInstance().addToRequestQueue(stringRequest);
    }
 
    @Override
    public void onClick(View v) {
        addUser();
    }
}

  • As you can see on the code, on successfull registration we are starting a new Activity named UserActivity. So create this activity. And inside the layout file of this activity (activity_user.xml) write the following xml code.

acitivity_user.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
<?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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="net.simplifiedcoding.gcmpushnotification.UserActivity">
 
 
    <TableLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_centerVertical="true">
 
        <TableRow>
 
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Id"
                android:textAppearance="?android:attr/textAppearanceLarge" />
 
            <TextView
                android:id="@+id/textViewId"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="1"
                android:textAppearance="?android:attr/textAppearanceLarge" />
 
        </TableRow>
 
 
        <TableRow>
 
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginRight="15dp"
                android:text="Name"
                android:textAppearance="?android:attr/textAppearanceLarge" />
 
            <TextView
                android:id="@+id/textViewName"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Belal Khan"
                android:textAppearance="?android:attr/textAppearanceLarge" />
 
        </TableRow>
 
 
        <TableRow>
 
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Email"
                android:textAppearance="?android:attr/textAppearanceLarge" />
 
            <TextView
                android:id="@+id/textViewEmail"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text=""
                android:textAppearance="?android:attr/textAppearanceLarge" />
 
        </TableRow>
 
    </TableLayout>
 
</RelativeLayout>

  • The above code will generate the following screen.
google cloud messaging tutorial

google cloud messaging tutorial

  • Now come inside the UserActivity.java file and write the following code.

UserActivity.java
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package net.simplifiedcoding.gcmpushnotification;
 
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
 
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
 
public class UserActivity extends AppCompatActivity {
 
    private TextView textViewId;
    private TextView textViewName;
    private TextView textViewEmail;
 
    private SharedPrefManager sharedPrefManager;
 
    private BroadcastReceiver mRegistrationBroadcastReceiver;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user);
 
        textViewId = (TextView) findViewById(R.id.textViewId);
        textViewName = (TextView) findViewById(R.id.textViewName);
        textViewEmail = (TextView) findViewById(R.id.textViewEmail);
 
        sharedPrefManager = new SharedPrefManager(this);
 
 
        textViewId.setText(String.valueOf(sharedPrefManager.getUserId()));
        textViewName.setText(sharedPrefManager.getUserName());
        textViewEmail.setText(sharedPrefManager.getUserEmail());
 
        mRegistrationBroadcastReceiver = new BroadcastReceiver() {
 
            //When the broadcast received
            //We are sending the broadcast from GCMRegistrationIntentService
 
            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent.getAction().equals(GCMRegistrationIntentService.REGISTRATION_SUCCESS)) {
                    Toast.makeText(getApplicationContext(), "Device is ready", Toast.LENGTH_LONG).show();
                } else if (intent.getAction().equals(GCMRegistrationIntentService.REGISTRATION_TOKEN_SENT)) {
                    Toast.makeText(getApplicationContext(), "Ready to receive push notifications", Toast.LENGTH_LONG).show();
                } else if (intent.getAction().equals(GCMRegistrationIntentService.REGISTRATION_ERROR)) {
                    Toast.makeText(getApplicationContext(), "GCM registration error!", Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(getApplicationContext(), "Error occurred", Toast.LENGTH_LONG).show();
                }
            }
        };
 
        int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
 
        if (ConnectionResult.SUCCESS != resultCode) {
            if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
                Toast.makeText(getApplicationContext(), "Google Play Service is not install/enabled in this device!", Toast.LENGTH_LONG).show();
                GooglePlayServicesUtil.showErrorNotification(resultCode, getApplicationContext());
 
            } else {
                Toast.makeText(getApplicationContext(), "This device does not support for Google Play Service!", Toast.LENGTH_LONG).show();
            }
        } else {
            Intent itent = new Intent(this, GCMRegistrationIntentService.class);
            startService(itent);
        }
    }
 
    @Override
    protected void onResume() {
        super.onResume();
        Log.w("MainActivity", "onResume");
        LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
                new IntentFilter(GCMRegistrationIntentService.REGISTRATION_SUCCESS));
        LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
                new IntentFilter(GCMRegistrationIntentService.REGISTRATION_ERROR));
    }
 
 
    @Override
    protected void onPause() {
        super.onPause();
        Log.w("MainActivity", "onPause");
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver);
    }
}

Adding Permission, Services and Receiver to AndroidManifest.xml

  • Now we need to add the above created service and receiver to our android manifest.xml. We also need to add some permission to our AndroidManifest.xml.

AndroidManifest.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="net.simplifiedcoding.gcmpushnotification">
 
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
 
    <permission
        android:name="net.simplifiedcoding.androidgcm.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />
 
    <uses-permission android:name="net.simplifiedcoding.androidgcm.permission.C2D_MESSAGE" />
 
    <application
        android:name=".MyApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
 
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
 
        <!--            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="com.gnirt69.gcmexample" />
            </intent-filter>
        </receiver>
 
        <!--             GCM Receiver Service -->
        <service
            android:name=".GCMPushReceiverService"
            android:exported="false">
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            </intent-filter>
        </service>
 
        <!--             GCM Registration Intent Service -->
        <service
            android:name=".GCMRegistrationIntentService"
            android:exported="false">
            <intent-filter>
                <action android:name="com.google.android.gms.iid.InstanceID" />
            </intent-filter>
        </service>
 
        <activity android:name=".UserActivity"></activity>
    </application>
 
</manifest>

  • Now just run your application. And if you are using My API you can test notifications by using My Web Panel by going to this link.
  • You can also download the source code of this google cloud messaging tutorial from below links.

Get Android Project 

Get Server Side PHP Project

So thats all for this Google Cloud Messaging Tutorial for Android. I will post more Google Cloud Messaging Tutorial s in upcoming posts for doing different tasks using GCM. If you liked this Google Cloud Messaging Tutorial please share it to your social networks. Thank You 🙂

Sharing is Caring:

  • Tweet
  • Share on Tumblr
  • More
  • Pocket
  • Print
  • Email

Related

Filed Under: Android Advance, Android Application Development Tagged With: android push notification gcm php, google cloud messaging php, google cloud messaging tutorial

About Belal Khan

I am Belal Khan, I am currently pursuing my MCA. In this blog I write tutorials and articles related to coding, app development, android etc.

Comments

  1. Marcelo says

    April 22, 2016 at 11:23 am

    Hi Belal, I want to ask you about a messege ( Google Play Service is not install/enabled in this device!” ) that appears in other device..
    I´m testing your code in 2 devices, One of them is my device. In this mobile all is ok..

    Then I tested in other mobile ( Samsung S3 ) It is not in use.. no chip.. It was restore to factory default. I only setup my gmail account into it.
    In this mobile I received the message Google Play Service is not install/enabled in this device!”

    What I must do in orde to solve it ???????????..

    I´m so happy with this tutorial… I will be very usefull for me

    Thanks a lot

    Reply
    • Hung Tran says

      May 2, 2016 at 8:23 am

      If you use genymotion: https://inthecheesefactory.com/blog/how-to-install-google-services-on-genymotion/en

      Reply
  2. Marcelo says

    April 22, 2016 at 4:32 pm

    Hi. Belal. As I told you before I´m testing this tutorial. All is ok but I realized that when registering a user, this is registered twice, one with token and the other without it.. Anyway notifications upto now is ok

    What is your opinion about this twice registrations ?

    See you

    Marcelo

    Reply
    • Belal Khan says

      April 22, 2016 at 5:27 pm

      You mean you are getting two rows in the database for the same user?

      Reply
  3. Marcelo says

    April 22, 2016 at 5:32 pm

    yes I am getting two rows in the database for the same user.

    The only different is one has token register and in the other is empty.

    Reply
    • Belal Khan says

      April 23, 2016 at 4:18 am

      You have done something wrong.. as my database is getting only one value.. and according to the php code.. I am preventing duplicate emails in mysql so it is not possible.
      You can see the admin panel I have given in the post. I am not getting double registration problem.

      Check the php part carefully

      Reply
  4. Marcelo says

    April 22, 2016 at 5:33 pm

    Hi, again.. When we clik over a notification we receive we are linking to a url…
    Where must I change this url ?

    Thanks

    Reply
  5. Marcelo says

    April 22, 2016 at 5:38 pm

    Hi, other Comment about twice rows in registration process.
    Sometimes we have two rows.. other times only one ( with token )
    That means not always we have two rows in our table

    What do you thinks about ?

    Marcelo

    Reply
  6. slim says

    April 22, 2016 at 9:51 pm

    hi belal,
    How to send a push notification to a user not connected and when he connects on any device he gets the notification ??

    Reply
  7. Vishal says

    April 23, 2016 at 3:56 am

    Hey Belal, Nice Code ..

    But there is one question how can we group users in this .

    Thank You.

    Reply
  8. nitish says

    April 23, 2016 at 5:09 am

    hello sir what modification should i make to host it on real server . free hosting like hostinger or is rest api supported or not there.

    Reply
  9. Muhammad yana Mulyana says

    April 23, 2016 at 8:32 am

    thank u for sharing.
    i have try your code name and email hav inserted to database but the token is empty.
    i have register to GCM and api is correct. where is the wrong.? thank you

    Reply
    • TechGirl says

      April 26, 2016 at 2:01 pm

      I also facing same.Do u got any solution?

      Reply
    • Shakawat Hossain says

      May 13, 2016 at 2:58 am

      Hi belal, how are you, hows your life.I ahve tried your code. There is no err but Not able to register. In the php send GCm.php i have set the server key also

      Reply
  10. Habibi says

    April 23, 2016 at 12:00 pm

    Hi, Belal, I’m new in Android Studio and native Android programming (but I already knew Eclipse since I started developing hybrid mobile app using Cordova and I have some experience in Java).
    I found your tutorial, and I must say that your approach is much simpler than others I ever read. Confusing part about developing Android app, IMHO is the link between Android “ecosystem” to another one (such as GCM), but you did good in explaining about that. It made me one of your regular blog reader.
    Keep up good posts !

    Reply
  11. Marcelo says

    April 23, 2016 at 4:00 pm

    Hi. I was testig sending notification while de device is off, and when the device turn on, the notification appear.
    For me all is ok
    I´m using Android 5.0.1 in LG G3 device

    Reply
    • nitish says

      April 23, 2016 at 5:53 pm

      hi is it working on real server

      Reply
    • Saurabhk says

      April 26, 2016 at 8:08 am

      CAN U MAIL ME FULL ANDROID WORKING CODE WITH BUILD APK AND PHP FILES – [email protected] i will thankful ur lots

      Reply
  12. MH Afridi says

    April 25, 2016 at 2:31 pm

    Respected Sir,

    I will be waiting with sound update for notifcation with Source Code
    Email: [email protected]

    Reply
    • Belal Khan says

      April 26, 2016 at 3:13 pm

      In GCMPushReceiverService.java
      You can see the method sendNotification

      This is the method used for creating notification .. to make sound add the following line to the notification builder
      Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
      builder.setSound(alarmSound);

      Reply
  13. Kholoud says

    April 26, 2016 at 6:18 am

    Thank you for good tutorail ,

    – when download SlIM and paste into my project , this file ‘.././libs/Slim/Slim.php’ not found .. what can I do ?

    – if my project no need to registration and push notification to all users , can I save only id and token number into database , I’m trying that but not work well ?

    thanks again

    Reply
    • Adrian says

      April 30, 2016 at 4:33 pm

      Did you manage to find any solution?

      Reply
    • adrian says

      May 1, 2016 at 2:25 am

      did u manage to find the solution?

      Reply
    • Shakawat Hossain says

      May 15, 2016 at 4:22 pm

      hi belal,
      your php server side script not working. I have created db and table and change config file also but your script not working

      Reply
  14. Saurabhk says

    April 26, 2016 at 8:02 am

    hey cn u share me ur full android code with a zip . [email protected] . and i have already copy paste ur php files on my server.

    Reply
  15. Marcelo says

    April 26, 2016 at 6:07 pm

    Thanks !!! Sound work ok

    Reply
    • Adrian says

      April 30, 2016 at 4:35 pm

      Can u show me how u modify the coding?

      Reply
  16. Marcelo says

    May 1, 2016 at 12:39 pm

    This is the code

    private void sendNotification(String message, String title) {
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    builder.setSmallIcon(R.mipmap.ic_launcher);
    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(“http://www.domain.com.”));
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
    builder.setContentIntent(pendingIntent);
    builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
    builder.setContentTitle(title);
    builder.setContentText(message);
    Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    builder.setSound(alarmSound);
    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    notificationManager.notify(1, builder.build());

    }

    Reply
  17. Gautam Pansheriya says

    May 2, 2016 at 9:00 am

    Oops! Some error occured How can i solved it pls help me ..

    Reply
  18. marcelo says

    May 2, 2016 at 7:47 pm

    Hi..i am using a Real device…not a emulator
    How can i solve this peoblem in a Real samsung galaxy €3
    Thanks

    Reply
  19. Ashwini says

    May 4, 2016 at 8:36 am

    Hii Belal,

    I am trying to test your demo apk on my mobile but i am getting force closed

    Reply
  20. Shakawat Hossain says

    May 15, 2016 at 4:51 pm

    when i run your script , its not add email from database to selector(combobox).
    Can you tell me what is the reson

    Reply
  21. Alejandro says

    May 20, 2016 at 11:59 am

    Hi! I have a problem, when i put the name and email by POST in http://localhost/PushNotification/v1/adduser its return always {“error”:true,”message”:”Email address is not valid”} Why?
    Thanks!

    Reply
  22. Alex says

    May 20, 2016 at 2:04 pm

    I have a problem. When i call http://localhost/TestNotifyAndroidMulti/v1/index.php/adduser?name=holaMundo&[email protected]

    return always that email is invalid.

    If i comment line //validateEmail($email);, the system return {“error”:true,”message”:”Oops! An error occurred while registereing”}

    Thanks

    Reply
  23. Paquito says

    May 22, 2016 at 5:55 pm

    I copy the code Android in my project and i have configured him with the changes of manigest but i have the next error.

    java.lang.NullPointerException: Attempt to invoke virtual method ‘void pruebanotifydos.alcales.app.pruebanotifydos.MyApplication.addToRequestQueue(com.android.volley.Request)’ on a null object reference at pruebanotifydos.alcales.app.pruebanotifydos.MainActivity.addUser(MainActivity.java:95)

    Anyone know why? Thanks

    Reply
    • Belal Khan says

      May 23, 2016 at 5:38 pm

      You haven’t added the singleton class MyApplication to your manifest Check my AndroidManifest.xml file. You have to add this class inside the application tag of your manifest file see below code or check my manifest code on the post
      <application
      <!– Add this line –>
      android:name=”.MyApplication”

      Reply
      • Paquito says

        May 23, 2016 at 9:17 pm

        Yeees!! Thanks!! ^^

        Reply
  24. hitamku says

    May 24, 2016 at 6:02 pm

    Please help
    I am create database on my web server and change config file, but i getting error column not show indexphp.
    I change user and pass
    Thanks u

    Reply
  25. Heri says

    May 25, 2016 at 1:43 am

    I have some problem when use this Web Panel on Centos 5.4.
    Please let me know what is the problems, if you can please check in :

    http://222.124.7.228/PushNotification/

    The database already create, but still not working.

    Thanks

    Reply
    • Belal Khan says

      May 25, 2016 at 1:49 am

      There is some problem with your data connection.. the link you given is showing this error at the bottom.. view the source of your page by pressing control + u (for google chrome) if you want to see the error

      Failed to connect to MySQL: Unknown database ‘db_pushnotification1’

      So check the database db_pushnotification1 exist or not

      Reply
      • Heri says

        May 25, 2016 at 1:55 am

        Thank you, but please check again, it’s still not working with different error

        Thanks

        Reply
  26. Thierno says

    May 30, 2016 at 3:58 pm

    Hi i have this problem, can you help me ?
    (soory i’m french excuse my english)

    :compileDebugJavaWithJavacC:\Users\tsarre\app\platforms\android\src\io\cordova\hellocordova\GCMRegistrationIntentService.java:78: error: diamond operator is not supported in -source 1.6
    Map params = new HashMap();
    ^
    (use -source 7 or higher to enable diamond operator)
    C:\Users\tsarre\app\platforms\android\src\io\cordova\hellocordova\MainActivity.java:111: error: diamond operator is not supported in -source 1.6
    Map params = new HashMap();
    ^
    (use -source 7 or higher to enable diamond operator)
    2 errors
    FAILED

    FAILURE: Build failed with an exception.

    * What went wrong:
    Execution failed for task ‘:compileDebugJavaWithJavac’.
    > Compilation failed; see the compiler error output for details.

    * Try:
    Run with –stacktrace option to get the stack trace. Run with –info or –debug option to get more log output.

    BUILD FAILED

    Reply
  27. norfarhan says

    May 31, 2016 at 10:25 am

    Why using slim framework? can I using laravel?

    Reply
    • Belal Khan says

      May 31, 2016 at 12:17 pm

      Yeah obviously you can use any framework you want

      Reply
  28. Nii says

    June 1, 2016 at 7:54 pm

    i get a failure message when i try sending a notification from the server side. What might be the issue??

    Reply
  29. Nilesh Gangadhar says

    June 2, 2016 at 7:27 am

    hi
    you have not send your string.xml file I am getting this error (R.string.gcm_defaultSenderId)

    Reply
  30. Nilesh Gangadhar says

    June 2, 2016 at 7:31 am

    Hi i have this problem in string.xml file (R.string.gcm_defaultSenderId)
    here i am getting error. can u send me ur string.xml file

    Reply
    • Belal Khan says

      June 2, 2016 at 9:00 am

      It is because you haven’t pasted google-services.json file..

      Reply
      • Gourav says

        June 9, 2016 at 10:15 am

        where to to past google-services.json file

        Reply
  31. Thierno Sarré says

    June 8, 2016 at 12:01 pm

    I don’t know why i have this error, plz help

    :compileDebugJavaWithJavacC:\Users\tsarre\gcmassistance\platforms\android\src\fr\assistance\free\GCMRegistrationIntentService.java:76: error: diamond operator is not supported in -source 1.6
    Map params = new HashMap();
    ^
    (use -source 7 or higher to enable diamond operator)
    C:\Users\tsarre\gcmassistance\platforms\android\src\fr\assistance\free\MainActivity.java:112: error: diamond operator is not supported in -source 1.6
    Map params = new HashMap();
    ^
    (use -source 7 or higher to enable diamond operator)
    C:\Users\tsarre\gcmassistance\platforms\android\src\io\cordova\hellocordova\MainActivity.java:112: error: diamond operator is not supported in -source 1.6
    Map params = new HashMap();
    ^
    (use -source 7 or higher to enable diamond operator)
    3 errors
    FAILED

    Reply
  32. Gourav says

    June 9, 2016 at 8:11 am

    Hello sir please help me , i am not getting any response while register but i can see the registered values in my server database table……………?

    Reply
  33. essra mohy mohamad says

    June 23, 2016 at 11:54 am

    Hi Belal,

    Can you tell me how i can using asp.net instead of php

    Reply
  34. sanders says

    July 8, 2016 at 8:17 am

    hai belal ,i have downloaded your code and registration is success but i am gettin error on send message from your link…

    Reply
  35. Pravin says

    July 15, 2016 at 8:09 am

    Code was running correctly on localhost but not on real server .it show empty token on database how to solve it please help me

    Reply
  36. kashyap says

    July 20, 2016 at 1:03 am

    Hey great tutorials , I really appreciate the way you annotate the use of each line of code ,
    so , my need is …. I need to send push notifications to devices using any GCM service provider so , i kind of understood how GCM works and all but im bit strucked here
    will the code part change for every service provider ? or can we make it dynamic ? can you have something for me ?

    thanks

    Reply
  37. shoaib says

    August 1, 2016 at 1:16 am

    why did you remove your webpanel??
    Please add it again 🙁

    Reply
  38. Manish Gupta says

    August 10, 2016 at 9:38 am

    i used your admin panel & your apk Bilal
    i can see my email id in the drop down.
    but when i click the send button. it says oops please try again every time.
    Can anyone help ?

    Reply
  39. fre says

    August 27, 2016 at 12:52 pm

    I copy the code Server in my project and i have configured him but when i try to register user i have the next error.
    Unexpected response code 500 for http://localhost/PushNotification/v1/adduser
    Anyone know why? Thanks

    Reply
  40. Sanjeeb says

    September 10, 2016 at 7:13 am

    Hi Belal,
    Thanks for sharing the amazing tutorial…got it working after some tweaking on the user registration side, as REST APIs wont work on my localhost for some reason, maybe not configured for .htaccess file…however pls keep up the good work 🙂

    Reply
    • Belal Khan says

      September 10, 2016 at 7:19 am

      You may need to enable the rewrite module of apache..

      Reply
  41. Rameez ajaz says

    October 1, 2016 at 7:30 am

    hey bilal ! i am having some confusions regarding the slim framework !! I create my php scripts on notepad !! Can i write this php script on notepad and run it ? will it create problems or not ? coz I dont want to use this framework !! thanks

    Reply
    • Belal Khan says

      October 1, 2016 at 9:02 am

      You can use any text editor.. notepad as well

      Reply
  42. johnny says

    November 2, 2016 at 7:35 pm

    Dear Belal Khan,

    please help my /v1/ folder always get this error :

    404 Page Not Found
    The page you are looking for could not be found. Check the address bar to ensure your URL is spelled correctly. If all else fails, you can visit our home page at the link below.

    Visit the Home Page

    I can add new user thru my android.

    thank you

    Reply
  43. manisha khatke says

    November 10, 2016 at 7:58 am

    hello ,
    When iam click on receive notification i am getting this error
    “E/Volley: [105] BasicNetwork.performRequest: Unexpected response code 404 for http://192.168.25.18:7080/PushNotification/adduser
    Please help ,e out iam new in android development

    Reply
  44. Nikhil Guttikonda says

    November 30, 2016 at 1:02 pm

    getting error in.. GCMPushReceiverService extends GcmListenerService class..
    & also unble to resolve gcm in import statement.. it display unused import statement..

    please help me…

    private void sendNotification(String message, String title) {
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
    builder.setSmallIcon(R.mipmap.ic_launcher);
    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(“https://www.simplifiedcoding.net”));
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
    builder.setContentIntent(pendingIntent);
    builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.about));
    builder.setContentTitle(title);
    builder.setContentText(message);
    NotificationManager notificationManager = (NotificationManager)getSystemService(con.NOTIFICATION_SERVICE);
    notificationManager.notify(1, builder.build());

    }

    Reply
    • Nikhil Guttikonda says

      November 30, 2016 at 1:04 pm

      please immediately replay me… Thank you in advance all remaining Java file are not raise error..

      Reply
  45. sameer says

    December 20, 2016 at 9:12 am

    curl_setopt($ch, CURLOPT_URL, ‘https://android.googleapis.com/gcm/send’);

    Here which one use URL?

    Reply
  46. Ritesh says

    August 3, 2017 at 11:37 am

    hi sir, i am getting error for Slim.php file in index.php file. how to debug it..

    Reply

Leave a Reply to Adrian Cancel reply

Your email address will not be published. Required fields are marked *

Search




Download our Android App

Simplified Coding in Google Play

About Me

Belal Khan

Hello I am Belal Khan, founder and owner of Simplified Coding. I am currently pursuing MCA from St. Xavier's College, Ranchi. I love to share my knowledge over Internet.

Connect With Me

Follow @codesimplified
Simplified Coding

Popular Tutorials

  • Android JSON Parsing – Retrieve From MySQL Database
  • Android Login and Registration Tutorial with PHP MySQL
  • Android Volley Tutorial – Fetching JSON Data from URL
  • Android Upload Image to Server using Volley Tutorial
  • Android TabLayout Example using ViewPager and Fragments
  • Retrieve Data From MySQL Database in Android using Volley
  • Firebase Cloud Messaging Tutorial for Android
  • Android Volley Tutorial – User Registration and Login
  • Android Upload Image to Server Using PHP MySQL
  • Android Navigation Drawer Example using Fragments




About Simplified Coding

Simplified Coding is a blog for all the students learning programming. We are providing various tutorials related to programming and application development. You can get various nice and simplified tutorials related to programming, app development, graphics designing and animation. We are trying to make these things simplified and entertaining. We are writing text tutorial and creating video and visual tutorials as well. You can check about the admin of the blog here and check out our sitemap

Quick Links

  • Advertise Here
  • Privacy Policy
  • Disclaimer
  • About
  • Contact Us
  • Write for Us

Categories

Android Advance Android Application Development Android Beginners Android Intermediate Ionic Framework Tutorial JavaScript Kotlin Android Others PHP Advance PHP Tutorial React Native

Copyright © 2017 · Simplified Coding· All rights Reserved. And Our Sitemap.All Logos & Trademark Belongs To Their Respective Owners·

loading Cancel
Post was not sent - check your email addresses!
Email check failed, please try again
Sorry, your blog cannot share posts by email.