Just follow these you will implement GCM
Step 1: Registering with Google Cloud Messaging
a.Goto
Google APIs Console page and create a new project. (If you haven’t created already otherwise it will take you to dashboard)
b.After creating project you can see the
project id in the url. Note down the project id which will be used as
SENDER ID in android project. (Example: in #project:00000000 after semicolon 460866929976 is the sender id)
Step 1:Register device with GCM Server
Register the device which is going to receive notification from GCM
/*GCM*/
GoogleCloudMessaging gcm;
String regId = "", err = "";
private String PROJECT_NUMBER = "............";
public class AsyncTaskGCMRegister extends AsyncTask<String, String,String> {
String UserEmail="";
@Override
protected void onPreExecute() {
}
@Override
protected String doInBackground(String... arg0) {
try {
if(!mUserName.getText().toString().equals("")&&!mUserName.getText().toString().equals(null))
UserEmail=mUserName.getText().toString();
else {
sharedPref = getActivity().getSharedPreferences(getResources().getString(R.string.tagUserPrefSession), 0);
UserEmail= sharedPref.getString("username", null);
if(UserEmail==null||UserEmail=="")
UserEmail="N/A";
}
/*GCM TRY & CATCH*/
gcm = GoogleCloudMessaging.getInstance(getActivity());
try {
if (!checkPlayServices())
getActivity().runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getActivity(), "Google Play Services not su
pported. Please install and configure Google Play Store.", Toast.LENGTH_LONG)
.show();
}
});
else {
Log.d("IM", "registration thread happening");
regId = gcm.register(PROJECT_NUMBER);
Log.d("IM", "id: " + regId);
getActivity().runOnUiThread(new Runnable() {
public void run() {
/*Toast.makeText(getActivity(), "Play Store.", Toast.LENGTH_LONG)
.show();*/
new AsynchroTask(getActivity(), getResources().getString(R.string.tagGCMSaveDevice))
.execute(getResources().getString(R.string.GCMSaveDeviceUrl) + UserEmail + "/" + regId + "/" + "M");
}
});
}
} catch (Exception e) {
err = e.toString();
Log.d("IM register", "io exception: ");
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String strFromDoInBg) {
}
}
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity());
if (resultCode != ConnectionResult.SUCCESS) {
return false;
}
return true;
}
Step 2:Android Manifest.xml
Add the permission,receiver and service for GCM
<permission
android:name="{package name}.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="{package name}.permission.C2D_MESSAGE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.USE_CREDENTIALS" />
<uses-permission android:name="android.permission.READ_OWNER_DATA" />
<!--GCM-->
<receiver
android:name=".Utils.GcmBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND"
android:enabled="true">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="**PackageName**" />
</intent-filter>
</receiver>
<service android:name=".Utils.GCMIntentService"
android:enabled="true"/>
<meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />
Step 3:GcmBroadcastReceiver.Java
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.WakefulBroadcastReceiver;
import android.widget.Toast;
/**
* Created by jayaprakash.s on 7/16/2015.
*/
public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//Toast.makeText(context, "GCMIntent Service Successful!", Toast.LENGTH_LONG).show();
// Explicitly specify that GcmIntentService will handle the intent.
ComponentName comp = new ComponentName(context.getPackageName(),
GCMIntentService.class.getName());
// Start the service, keeping the device awake while it is launching.
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
Step 4: GCMIntentService.Java
/**
* Created by jayaprakash.s on 7/16/2015.
*/
import **PackageName**.MainActivity;
import **PackageName**.R;
import **PackageName**.helperclass.NotificationHandler;
import com.google.android.gcm.GCMBaseIntentService;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.util.Log;
import java.util.logging.Handler;
import java.util.logging.LogRecord;
public class GCMIntentService extends GCMBaseIntentService {
static int count = 0;
public GCMIntentService() {
super("GcmIntentService");
}
@Override
protected void onError(Context arg0, String error) {
Log.d("ApphoshiesFramework", "onError: " + error);
}
@Override
protected void onRegistered(Context context, String regId) {
Log.d("ApphoshiesFramework", "onRegistered: " + regId);
//DeviceToken.registerDeviceForGCM(context, regId);
}
@Override
protected void onUnregistered(Context context, String regId) {
Log.d("ApphoshiesFramework", "onUnregistered: " + regId);
//DeviceToken.unregisterDeviceFromGCM(context, regId);
}
@Override
protected void onMessage(Context context, Intent intent) {
Log.d("ApphoshiesFramework", "onMessage");
// Please customize!
// This is how to get values from the push message (data)
String message = intent.getStringExtra("message");
if(!message.equals("")&&!message.equals(null)){
long timestamp = intent.getLongExtra("timestamp", -1);
if (!message.equals("") && !message.equals(null)) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent resultIntent = new Intent(context, MainActivity.class);
resultIntent.putExtra("GCM", message);
resultIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPending = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Bitmap notificationLargeIconBitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.app_icon);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
.setAutoCancel(true)
.setSound(uri)
.setVibrate(new long[]{1000, 1000})
.setColor(context.getResources().getColor(R.color.ecstasy))
.setLargeIcon(notificationLargeIconBitmap)
.setSmallIcon(R.drawable.app_icon, 5) // notification icon
.setContentTitle("Notification") // main title of the notification
.setContentText(message) // notification text
.setContentIntent(resultPending);
NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle();
bigTextStyle.setBigContentTitle("Notification");
bigTextStyle.bigText(message);
mBuilder.setStyle(bigTextStyle);
notificationManager.notify(5, mBuilder.build());
}
}
}
}