Last active
August 29, 2015 14:13
-
-
Save hitenpratap/f7a090f1ebb4d176e98d to your computer and use it in GitHub Desktop.
Android Code For GCM Intent Service
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.hprog99.android; | |
import android.app.IntentService; | |
import android.app.NotificationManager; | |
import android.app.PendingIntent; | |
import android.content.Context; | |
import android.content.Intent; | |
import android.os.Bundle; | |
import android.os.SystemClock; | |
import android.support.v4.app.NotificationCompat; | |
import android.util.Log; | |
import com.google.android.gms.gcm.GoogleCloudMessaging; | |
public class GCMNotificationIntentService extends IntentService { | |
public static final int NOTIFICATION_ID = 1; | |
private NotificationManager mNotificationManager; | |
NotificationCompat.Builder builder; | |
public GCMNotificationIntentService() { | |
super("GcmIntentService"); | |
} | |
public static final String TAG = "GCMNotificationIntentService"; | |
@Override | |
protected void onHandleIntent(Intent intent) { | |
Bundle extras = intent.getExtras(); | |
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this); | |
String messageType = gcm.getMessageType(intent); | |
if (!extras.isEmpty()) { | |
if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR | |
.equals(messageType)) { | |
sendNotification("Send error: " + extras.toString()); | |
} else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED | |
.equals(messageType)) { | |
sendNotification("Deleted messages: " | |
+ extras.toString()); | |
} else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE | |
.equals(messageType)) { | |
sendNotification("Message Received from Google GCM Server: " | |
+ extras.get(Config.MESSAGE_KEY)); | |
Log.i(TAG, "Received: " + extras.toString()); | |
} | |
} | |
GcmBroadcastReceiver.completeWakefulIntent(intent); | |
} | |
private void sendNotification(String msg) { | |
Log.d(TAG, "Preparing to send notification...: " + msg); | |
mNotificationManager = (NotificationManager) this | |
.getSystemService(Context.NOTIFICATION_SERVICE); | |
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, | |
new Intent(this, MainActivity.class), 0); | |
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder( | |
this).setSmallIcon(R.drawable.hprog99) | |
.setContentTitle("GCM Notification") | |
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg)) | |
.setContentText(msg); | |
mBuilder.setContentIntent(contentIntent); | |
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build()); | |
Log.d(TAG, "Notification sent successfully."); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment