Google Cloud Messaging example in Android | Push notification demo with php back-end

Today I am going to share very Important code for GCM(Google Cloud Messaging) for Android. I worked with my php developer(Ankit Garg) for back end and it is working Okay for me.
My article have 3 category-

1)Creating a Google API Project
2)PHP Back-end
3)Android Front-end




                                                         Part-A  Google API Project

1)Open Google API console from here
2)If you have not created any project create new project for your application-

3)See your browser URL and note your project ID from above some thing like that-1080127563513
4)In the main Google APIs Console page, select Services.
5)Turn the Google Cloud Messaging toggle to ON.
6)In the Terms of Service page, accept the terms.
7)get API Key from main Google APIs Console page, select API Access. You will see a screen that resembles the following and click on Create new Server Key:

8)Now from below window choose create button:

9)From below window note your project id and api key:
 

 

Part-B PHP Back-end Side


 
Just copy below file and put into your  php server inside ws folder-

1)GCM.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
<?php
$regID=$_GET['regID'];
$registatoin_ids=array($regID);
$msg=array("message"=>'HI Manish');
$fields=array
 (
  'registration_ids'=>$registatoin_ids,
  'data'=>$msg
 );
$headers=array
 (
  'Authorization: key=AIzaSyA46UE7bBWXCpHSD5sbNxbRwI1MAKVI-jg',
  'Content-Type: application/json'
 );
$ch=curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
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);
echo $result;
?>
Part-C Android side

1)MainActivity.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
package com.manish.gcm.push;
import static com.manish.gcm.push.CommonUtilities.SENDER_ID;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import com.google.android.gcm.GCMRegistrar;
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public class MainActivity extends Activity {
 private String TAG = "** GCMPushDEMOAndroid**";
 private TextView mDisplay;
 String regId = "";
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  checkNotNull(SENDER_ID, "SENDER_ID");
  GCMRegistrar.checkDevice(this);
  GCMRegistrar.checkManifest(this);
  mDisplay = (TextView) findViewById(R.id.textView1);
  regId = GCMRegistrar.getRegistrationId(this);
  if (regId.equals("")) {
   GCMRegistrar.register(this, SENDER_ID);
  } else {
   Log.v(TAG, "Already registered");
  }
  /**
   * call asYnc Task
   */
  new sendIdOnOverServer().execute();
  mDisplay.setText("RegId=" + regId);
 }
 private void checkNotNull(Object reference, String name) {
  if (reference == null) {
   throw new NullPointerException(getString(R.string.error_config,
     name));
  }
 }
 @Override
 protected void onPause() {
  super.onPause();
  GCMRegistrar.unregister(this);
 }
 public class sendIdOnOverServer extends AsyncTask<string string="" void=""> {
  ProgressDialog pd = null;
  @Override
  protected void onPreExecute() {
   pd = ProgressDialog.show(MainActivity.this, "Please wait",
     "Loading please wait..", true);
   pd.setCancelable(true);
  }
  @Override
  protected String doInBackground(String... params) {
   try {
    HttpResponse response = null;
    HttpParams httpParameters = new BasicHttpParams();
    HttpClient client = new DefaultHttpClient(httpParameters);
    String url = "http://10.0.0.30//parsing/GCM.php?" + "&regID="
      + regId;
    Log.i("Send URL:", url);
    HttpGet request = new HttpGet(url);
    response = client.execute(request);
    BufferedReader rd = new BufferedReader(new InputStreamReader(
      response.getEntity().getContent()));
    String webServiceInfo = "";
    while ((webServiceInfo = rd.readLine()) != null) {
     Log.d("****Status Log***", "Webservice: " + webServiceInfo);
    }
   } catch (Exception e) {
    e.printStackTrace();
   }
   return null;
  }
  @Override
  protected void onPostExecute(String result) {
   pd.dismiss();
  }
 }
}
</string>

2)GCMIntentService.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
package com.manish.gcm.push;
import static com.manish.gcm.push.CommonUtilities.SENDER_ID;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import com.google.android.gcm.GCMBaseIntentService;
public class GCMIntentService extends GCMBaseIntentService {
 public GCMIntentService() {
  super(SENDER_ID);
 }
 private static final String TAG = "===GCMIntentService===";
 @Override
 protected void onRegistered(Context arg0, String registrationId) {
  Log.i(TAG, "Device registered: regId = " + registrationId);
 }
 @Override
 protected void onUnregistered(Context arg0, String arg1) {
  Log.i(TAG, "unregistered = " + arg1);
 }
 @Override
 protected void onMessage(Context context, Intent intent) {
  Log.i(TAG, "new message= ");
  String message = intent.getExtras().getString("message");
  generateNotification(context, message);
 }
 @Override
 protected void onError(Context arg0, String errorId) {
  Log.i(TAG, "Received error: " + errorId);
 }
 @Override
 protected boolean onRecoverableError(Context context, String errorId) {
  return super.onRecoverableError(context, errorId);
 }
 /**
  * Issues a notification to inform the user that server has sent a message.
  */
 private static void generateNotification(Context context, String message) {
  int icon = R.drawable.ic_launcher;
  long when = System.currentTimeMillis();
  NotificationManager notificationManager = (NotificationManager) context
    .getSystemService(Context.NOTIFICATION_SERVICE);
  Notification notification = new Notification(icon, message, when);
  String title = context.getString(R.string.app_name);
  Intent notificationIntent = new Intent(context, MainActivity.class);
  notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
    | Intent.FLAG_ACTIVITY_SINGLE_TOP);
  PendingIntent intent = PendingIntent.getActivity(context, 0,
    notificationIntent, 0);
  notification.setLatestEventInfo(context, title, message, intent);
  notification.flags |= Notification.FLAG_AUTO_CANCEL;
  notificationManager.notify(0, notification);
 }
}

3)CommonUtilities .java

1
2
3
4
5
6
7
package com.manish.gcm.push;
public final class CommonUtilities {
//put here your sender Id
static final String SENDER_ID = "311451115764";
}

4)activity_main.xml

1
2
3
4
5
<relativelayout android:layout_height="match_parent" android:layout_width="match_parent" tools:context=".MainActivity" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools">
    <textview android:id="@+id/textView1" android:layout_centerhorizontal="true" android:layout_centervertical="true" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="@string/hello_world">
</textview></relativelayout>

5)manifest.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
<manifest android:versioncode="1" android:versionname="1.0" package="com.manish.gcm.push" xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-sdk android:minsdkversion="7" android:targetsdkversion="16">
    <permission android:name="com.manish.gcm.push.permission.C2D_MESSAGE" android:protectionlevel="signature">
    <uses-permission android:name="com.manish.gcm.push.permission.C2D_MESSAGE">
    <uses-permission android:name="android.permission.GET_ACCOUNTS">
    <uses-permission android:name="android.permission.WAKE_LOCK">
    <uses-permission android:name="android.permission.INTERNET">
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE">
    <application android:allowbackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme">
        <activity android:label="@string/app_name" android:name="com.manish.gcm.push.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN">
                <category android:name="android.intent.category.LAUNCHER">
            </category></action></intent-filter>
        </activity>
        <receiver android:name="com.google.android.gcm.GCMBroadcastReceiver" android:permission="com.google.android.c2dm.permission.SEND">
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE">
                <action android:name="com.google.android.c2dm.intent.REGISTRATION">
                <category android:name="com.manish.gcm.push">
            </category></action></action></intent-filter>
        </receiver>
        <service android:name=".GCMIntentService">
    </service></application>
</uses-permission></uses-permission></uses-permission></uses-permission></uses-permission></permission></uses-sdk></manifest><a href="https://github.com/manishsri01/GCMPushDemo" target="_blank">
</a>

6)Download Zip Code

Thanks,

Advertisements

Leave a Reply

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

WordPress.com Logo

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

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s