Follow the Below Steps
-------------------------
Create a Google API Project
------------------------------
-----------------------------------
goes Services and turn the Google Cloud Messaging for Android toggle to ON
Generate API Key
--------------------
goes to API Access
click new Android key, then window will be opened, enter your SHA1 key along with your project package name then click on create button
you will get an api key, copy this key and use it in later
MainActivity.java
-------------------
public class MainActivityextends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (isNetworkAvailable()) {
if(GCMMessaging.getRegistrationId(MainActivity.this).equals("n/a"))
{
GCMMessaging.requestRegistration(SplashSceen.this);
}
}
else{
Toast.makeText(getApplicationContext(),"No network connection ",3000).show();
}
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager
.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
}
}
MyIntentService
-------------------
public class MyIntentService extends IntentService {
@SuppressWarnings("unused")
private String senderId = Constants.senderId;
private static int NOTIFICATION_ID = 1;
private static PowerManager.WakeLock sWakeLock;
static String TAG = "MyIntentService";
public MyIntentService() {
super("MyService");
// TODO Auto-generated constructor stub
}
public MyIntentService(String senderId) {
// senderId is used as base name for threads, etc.
super(senderId);
this.senderId = senderId;
}
private static final Object LOCK = MyIntentService.class;
static void runIntentInService(Context context, Intent intent) {
synchronized (LOCK) {
Log.v(TAG, "runIntentInService1");
if (sWakeLock == null) {
PowerManager pm = (PowerManager) context
.getSystemService(Context.POWER_SERVICE);
sWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"my_wakelock");
}
}
sWakeLock.acquire();
intent.setClassName(context, MyIntentService.class.getName());
context.startService(intent);
Log.v(TAG, "runIntentInService finish");
}
@Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
try {
String action = intent.getAction();
Log.v(TAG, "onHandleIntent" + action);
if (action.equals("com.google.android.c2dm.intent.REGISTRATION")) {
Log.v(TAG, "REGISTRATION");
handleRegistration(MyIntentService.this, intent);
} else if (action.equals("com.google.android.c2dm.intent.RECEIVE")) {
handleMessage(MyIntentService.this, intent);
Log.v(TAG, "RECEIVE MESSAGE");
} else if (action.equals("com.google.android.c2dm.intent.RETRY")) {
GCMMessaging.requestRegistration(MyIntentService.this);
Log.v(TAG, "RETRY");
}
} finally {
synchronized (LOCK) {
sWakeLock.release();
}
}
}
private void handleRegistration(Context context, Intent intent) {
String registration = intent.getStringExtra("registration_id");
if (intent.getStringExtra("error") != null) {
// Registration failed, should try again later.
Log.d("GCM", "registration failed");
String error = intent.getStringExtra("error");
if (error == "SERVICE_NOT_AVAILABLE") {
Log.d("GCM", "SERVICE_NOT_AVAILABLE");
} else if (error == "ACCOUNT_MISSING") {
Log.d("GCM", "ACCOUNT_MISSING");
} else if (error == "AUTHENTICATION_FAILED") {
Log.d("GCM", "AUTHENTICATION_FAILED");
} else if (error == "TOO_MANY_REGISTRATIONS") {
Log.d("GCM", "TOO_MANY_REGISTRATIONS");
} else if (error == "INVALID_SENDER") {
Log.d("GCM", "INVALID_SENDER");
} else if (error == "PHONE_REGISTRATION_ERROR") {
Log.d("GCM", "PHONE_REGISTRATION_ERROR");
} else {
Log.d("GCM", "REGISTRATION_ERROR");
}
Editor editor = context.getSharedPreferences(Constants.KEY,
Context.MODE_PRIVATE).edit();
editor.putString(Constants.REGISTRATION_KEY, "n/a");
editor.putString(Constants.ERROR_DESC, error);
editor.commit();
} else if (intent.getStringExtra("unregistered") != null) {
// unregistration done, new messages from the authorized sender will
// be rejected
Log.d("GCM", "unregistered");
unregisterWithServer(context);
} else if (registration != null) {
Log.d("GCM registration ! null", registration);
saveRegistrationId(context, registration);
sendRegistrationIdToServer(registration);
}
}
private void handleMessage(Context context, Intent intent) {
Log.v("############GCM############", "Received message");
Intent intent1;
// String message = intent.getStringExtra("data");
// String s=message.toString();
String data = intent.getExtras().getString("message");
String type = intent.getStringExtra("type");
Intent intent =new Intent();
Log.v("############GCM##############", "dmControl: message = " + data);
// TODO Send this to my application server to get the real data
// Lets make something visible to show that we received the message
createNotification(context, data, type,intent);
}
private void saveRegistrationId(Context context, String registrationId) {
Log.v("GCM saveregistration id", registrationId);
Editor editor = context.getSharedPreferences(Constants.KEY,
Context.MODE_PRIVATE).edit();
editor.putString(Constants.REGISTRATION_KEY, registrationId);
editor.putString(Constants.ERROR_DESC, "null");
editor.commit();
}
// public void sendRegistrationIdToServer(String deviceId,String
// registrationId)
public void sendRegistrationIdToServer(String registrationId) {
Log.v("GCM", "Sending registration ID to my application server");
// write code for your webservice
}
@SuppressWarnings("deprecation")
public void createNotification(Context context, String data, String type,Intent intent) {
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.ic_launcher,
"Title" + data, System.currentTimeMillis());
// Hide the notification after its selected
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.defaults |= Notification.DEFAULT_SOUND;
PendingIntent pendingIntent = PendingIntent.getActivity(context,
NOTIFICATION_ID, intent, PendingIntent.FLAG_UPDATE_CURRENT);
notification.setLatestEventInfo(context, "title", "" + data,
pendingIntent);
notificationManager.notify(NOTIFICATION_ID++, notification);
}
private void unregisterWithServer(Context context) {
// TODO Auto-generated method stub
}
}
GCMMessaging
------------------
public class GCMMessaging {
private static final long DEFAULT_BACKOFF = 30000;
public static final String BACKOFF = "backoff";
static final String PREFERENCE = "exp_back_off";
static String tag = "Messaging class";
static long getBackoff(Context context) {
final SharedPreferences prefs = context.getSharedPreferences(
PREFERENCE,
Context.MODE_PRIVATE);
return prefs.getLong(BACKOFF, DEFAULT_BACKOFF);
}
static void setBackoff(Context context, long backoff) {
final SharedPreferences prefs = context.getSharedPreferences(
PREFERENCE,
Context.MODE_PRIVATE);
Editor editor = prefs.edit();
editor.putLong(BACKOFF, backoff);
editor.commit();
}
public static void requestRegistration(Context context) {
// TODO Auto-generated method stub
Log.v(tag, "requestRegistrationId method called sender id");
Intent intent = new Intent("com.google.android.c2dm.intent.REGISTER");
intent.putExtra("app",
PendingIntent.getBroadcast(context, 0, new Intent(), 0));
// Sender id - project ID generated when signing up
intent.putExtra("sender", Constants.senderId);
context.startService(intent);
}
public static String getRegistrationId(Context context) {
SharedPreferences prefs = context.getSharedPreferences(Constants.KEY,Context.MODE_PRIVATE);
String registraionId = prefs.getString(Constants.REGISTRATION_KEY, "n/a");
return registraionId;
}
public static void removeRegistrationId(Context context) {
SharedPreferences settings = context.getSharedPreferences(Constants.KEY,Context.MODE_PRIVATE);
SharedPreferences.Editor edit = settings.edit();
edit.putString(Constants.REGISTRATION_KEY, "n/a"); // registration id
edit.commit(); //apply
}
}
GCMReceiver
-----------------
public class GCMReceiver extends BroadcastReceiver
{
Context context;
String TAG = "GCM receiver";
@Override
public void onReceive(Context context, Intent intent) {
Log.v(TAG, "Registration Receiver called");
Log.v("#############"+TAG+"###############", "Receiver: "+intent.getAction());
this.context = context;
MyIntentService.runIntentInService(context, intent);
setResult(Activity.RESULT_OK, null, null);
}
}
Constants.java
------------------
public class Constants
{
public static String senderId="enter your project id";
public static String KEY = "enter your key";
public static String REGISTRATION_KEY = "n/a";
public static String ERROR_DESC = "errorDesc";*/
}
write permissions in manifest file
-----------------------------------
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<!-- Creates a custom permission so only this app can receive its messages. -->
<permission
android:name="packagename.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="packagename.permission.C2D_MESSAGE" />
<!-- This app has permission to register and receive data message. -->
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
copy services
----------------
<receiver
android:name="packageName.GCMReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
- <!-- Receive the actual message -->
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="packageName" />
</intent-filter>
- <!-- Receive the registration id -->
- <intent-filter>
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="packageName" />
</intent-filter>
</receiver>
<service android:name="packageName.MyIntentService" />
Server side Code
-------------------
write code for sending message,device token and api key to GCMServer from your server
-------------------------
Create a Google API Project
------------------------------
- Open the Google Cloud Console.
- If you haven't created an API project yet, click Create Project.
- Add project name and click Create.
- Once the project has been created, a page appears that displays your project ID and project number.
- Copy your project number, this is your GCM sendeIdnumber
-----------------------------------
goes Services and turn the Google Cloud Messaging for Android toggle to ON
Generate API Key
--------------------
goes to API Access
click new Android key, then window will be opened, enter your SHA1 key along with your project package name then click on create button
you will get an api key, copy this key and use it in later
MainActivity.java
-------------------
public class MainActivityextends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (isNetworkAvailable()) {
if(GCMMessaging.getRegistrationId(MainActivity.this).equals("n/a"))
{
GCMMessaging.requestRegistration(SplashSceen.this);
}
}
else{
Toast.makeText(getApplicationContext(),"No network connection ",3000).show();
}
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager
.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
}
}
MyIntentService
-------------------
public class MyIntentService extends IntentService {
@SuppressWarnings("unused")
private String senderId = Constants.senderId;
private static int NOTIFICATION_ID = 1;
private static PowerManager.WakeLock sWakeLock;
static String TAG = "MyIntentService";
public MyIntentService() {
super("MyService");
// TODO Auto-generated constructor stub
}
public MyIntentService(String senderId) {
// senderId is used as base name for threads, etc.
super(senderId);
this.senderId = senderId;
}
private static final Object LOCK = MyIntentService.class;
static void runIntentInService(Context context, Intent intent) {
synchronized (LOCK) {
Log.v(TAG, "runIntentInService1");
if (sWakeLock == null) {
PowerManager pm = (PowerManager) context
.getSystemService(Context.POWER_SERVICE);
sWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"my_wakelock");
}
}
sWakeLock.acquire();
intent.setClassName(context, MyIntentService.class.getName());
context.startService(intent);
Log.v(TAG, "runIntentInService finish");
}
@Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
try {
String action = intent.getAction();
Log.v(TAG, "onHandleIntent" + action);
if (action.equals("com.google.android.c2dm.intent.REGISTRATION")) {
Log.v(TAG, "REGISTRATION");
handleRegistration(MyIntentService.this, intent);
} else if (action.equals("com.google.android.c2dm.intent.RECEIVE")) {
handleMessage(MyIntentService.this, intent);
Log.v(TAG, "RECEIVE MESSAGE");
} else if (action.equals("com.google.android.c2dm.intent.RETRY")) {
GCMMessaging.requestRegistration(MyIntentService.this);
Log.v(TAG, "RETRY");
}
} finally {
synchronized (LOCK) {
sWakeLock.release();
}
}
}
private void handleRegistration(Context context, Intent intent) {
String registration = intent.getStringExtra("registration_id");
if (intent.getStringExtra("error") != null) {
// Registration failed, should try again later.
Log.d("GCM", "registration failed");
String error = intent.getStringExtra("error");
if (error == "SERVICE_NOT_AVAILABLE") {
Log.d("GCM", "SERVICE_NOT_AVAILABLE");
} else if (error == "ACCOUNT_MISSING") {
Log.d("GCM", "ACCOUNT_MISSING");
} else if (error == "AUTHENTICATION_FAILED") {
Log.d("GCM", "AUTHENTICATION_FAILED");
} else if (error == "TOO_MANY_REGISTRATIONS") {
Log.d("GCM", "TOO_MANY_REGISTRATIONS");
} else if (error == "INVALID_SENDER") {
Log.d("GCM", "INVALID_SENDER");
} else if (error == "PHONE_REGISTRATION_ERROR") {
Log.d("GCM", "PHONE_REGISTRATION_ERROR");
} else {
Log.d("GCM", "REGISTRATION_ERROR");
}
Editor editor = context.getSharedPreferences(Constants.KEY,
Context.MODE_PRIVATE).edit();
editor.putString(Constants.REGISTRATION_KEY, "n/a");
editor.putString(Constants.ERROR_DESC, error);
editor.commit();
} else if (intent.getStringExtra("unregistered") != null) {
// unregistration done, new messages from the authorized sender will
// be rejected
Log.d("GCM", "unregistered");
unregisterWithServer(context);
} else if (registration != null) {
Log.d("GCM registration ! null", registration);
saveRegistrationId(context, registration);
sendRegistrationIdToServer(registration);
}
}
private void handleMessage(Context context, Intent intent) {
Log.v("############GCM############", "Received message");
Intent intent1;
// String message = intent.getStringExtra("data");
// String s=message.toString();
String data = intent.getExtras().getString("message");
String type = intent.getStringExtra("type");
Intent intent =new Intent();
Log.v("############GCM##############", "dmControl: message = " + data);
// TODO Send this to my application server to get the real data
// Lets make something visible to show that we received the message
createNotification(context, data, type,intent);
}
private void saveRegistrationId(Context context, String registrationId) {
Log.v("GCM saveregistration id", registrationId);
Editor editor = context.getSharedPreferences(Constants.KEY,
Context.MODE_PRIVATE).edit();
editor.putString(Constants.REGISTRATION_KEY, registrationId);
editor.putString(Constants.ERROR_DESC, "null");
editor.commit();
}
// public void sendRegistrationIdToServer(String deviceId,String
// registrationId)
public void sendRegistrationIdToServer(String registrationId) {
Log.v("GCM", "Sending registration ID to my application server");
// write code for your webservice
}
@SuppressWarnings("deprecation")
public void createNotification(Context context, String data, String type,Intent intent) {
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.ic_launcher,
"Title" + data, System.currentTimeMillis());
// Hide the notification after its selected
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.defaults |= Notification.DEFAULT_SOUND;
PendingIntent pendingIntent = PendingIntent.getActivity(context,
NOTIFICATION_ID, intent, PendingIntent.FLAG_UPDATE_CURRENT);
notification.setLatestEventInfo(context, "title", "" + data,
pendingIntent);
notificationManager.notify(NOTIFICATION_ID++, notification);
}
private void unregisterWithServer(Context context) {
// TODO Auto-generated method stub
}
}
GCMMessaging
------------------
public class GCMMessaging {
private static final long DEFAULT_BACKOFF = 30000;
public static final String BACKOFF = "backoff";
static final String PREFERENCE = "exp_back_off";
static String tag = "Messaging class";
static long getBackoff(Context context) {
final SharedPreferences prefs = context.getSharedPreferences(
PREFERENCE,
Context.MODE_PRIVATE);
return prefs.getLong(BACKOFF, DEFAULT_BACKOFF);
}
static void setBackoff(Context context, long backoff) {
final SharedPreferences prefs = context.getSharedPreferences(
PREFERENCE,
Context.MODE_PRIVATE);
Editor editor = prefs.edit();
editor.putLong(BACKOFF, backoff);
editor.commit();
}
public static void requestRegistration(Context context) {
// TODO Auto-generated method stub
Log.v(tag, "requestRegistrationId method called sender id");
Intent intent = new Intent("com.google.android.c2dm.intent.REGISTER");
intent.putExtra("app",
PendingIntent.getBroadcast(context, 0, new Intent(), 0));
// Sender id - project ID generated when signing up
intent.putExtra("sender", Constants.senderId);
context.startService(intent);
}
public static String getRegistrationId(Context context) {
SharedPreferences prefs = context.getSharedPreferences(Constants.KEY,Context.MODE_PRIVATE);
String registraionId = prefs.getString(Constants.REGISTRATION_KEY, "n/a");
return registraionId;
}
public static void removeRegistrationId(Context context) {
SharedPreferences settings = context.getSharedPreferences(Constants.KEY,Context.MODE_PRIVATE);
SharedPreferences.Editor edit = settings.edit();
edit.putString(Constants.REGISTRATION_KEY, "n/a"); // registration id
edit.commit(); //apply
}
}
GCMReceiver
-----------------
public class GCMReceiver extends BroadcastReceiver
{
Context context;
String TAG = "GCM receiver";
@Override
public void onReceive(Context context, Intent intent) {
Log.v(TAG, "Registration Receiver called");
Log.v("#############"+TAG+"###############", "Receiver: "+intent.getAction());
this.context = context;
MyIntentService.runIntentInService(context, intent);
setResult(Activity.RESULT_OK, null, null);
}
}
Constants.java
------------------
public class Constants
{
public static String senderId="enter your project id";
public static String KEY = "enter your key";
public static String REGISTRATION_KEY = "n/a";
public static String ERROR_DESC = "errorDesc";*/
}
write permissions in manifest file
-----------------------------------
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<!-- Creates a custom permission so only this app can receive its messages. -->
<permission
android:name="packagename.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="packagename.permission.C2D_MESSAGE" />
<!-- This app has permission to register and receive data message. -->
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
copy services
----------------
<receiver
android:name="packageName.GCMReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
- <!-- Receive the actual message -->
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="packageName" />
</intent-filter>
- <!-- Receive the registration id -->
- <intent-filter>
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="packageName" />
</intent-filter>
</receiver>
<service android:name="packageName.MyIntentService" />
Server side Code
-------------------
write code for sending message,device token and api key to GCMServer from your server