Skip to content

Instantly share code, notes, and snippets.

@devrath
Created May 11, 2016 06:11
Show Gist options
  • Select an option

  • Save devrath/cf36b71faa863da59df81ce4204c48e3 to your computer and use it in GitHub Desktop.

Select an option

Save devrath/cf36b71faa863da59df81ce4204c48e3 to your computer and use it in GitHub Desktop.
Simple GCM Integration
// In the OnCreate Method Start a background thread
new LongOperation().execute("");
private class LongOperation extends AsyncTask<String, Integer, String> {
@Override
protected void onPreExecute() {
// ******Perform the UI changes******//
}
@Override
protected String doInBackground(String... params) {
// ******Perform the background operation******//
try{
//----- GCM PART------->
if (gcmObj == null) {
gcmObj = GoogleCloudMessaging.getInstance(getApplicationContext());
}
regId = gcmObj.register(Constants.GOOGLE_PROJ_ID);
//----- GCM PART------->
}catch (Exception ex){
ex.printStackTrace();
}
return "Executed";
}
@Override
protected void onPostExecute(String result) {
// ******Perform the UI changes******//
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
`GcmBroadcastReceiver.java`
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.content.WakefulBroadcastReceiver;
/**
* Created by Devrath on 10-05-2016.
*/
public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
static Bitmap message_bitmap = null;
String mText;
String mUrl;
int mUrlType;
String finalImg;
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("com.google.android.c2dm.intent.RECEIVE")) {
handleMessage(context, intent);
}
ComponentName comp = new ComponentName(context.getPackageName(),
GCMNotificationIntentService.class.getName());
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
private void handleMessage(Context context, Intent intent) {
Bundle message = intent.getExtras();
String s= message.getString("the_message");
messageNotificationStringOnly(context,intent);
}
private void messageNotificationStringOnly(Context context, Intent intent) {
/* try {
Date date = new Date();
int notification_id = (int) date.getTime();
if(intent.getExtras()!=null){
Bundle message = intent.getExtras();
String s= message.getString("the_message");
*//*JSONObject strObj=new JSONObject(s);
Log.d("Json", strObj.toString());*//*
*//*String mText=strObj.get("text").toString();
String mUrl=strObj.get("imageurl").toString();
int mUrlType=strObj.getInt("imagetype");*//*
final Intent emptyIntent = new Intent(context,ActMain.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, notification_id, emptyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.notification_logo)
.setContentTitle(context.getResources().getString(R.string.screenname_apptitle))
.setContentText(s)
.setAutoCancel(true)
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(s))
.setContentIntent(pendingIntent);
// Set Vibrate, Sound and Light
int defaults = 0;
defaults = defaults | Notification.DEFAULT_SOUND | Notification.FLAG_AUTO_CANCEL;
mBuilder.setDefaults(defaults);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(notification_id, mBuilder.build());
*//*Toast.makeText(context.getApplicationContext(),
"\n message : " + message, 1).show();*//*
NotificationManager objNotfManager = (NotificationManager) context
.getApplicationContext().getSystemService(
Context.NOTIFICATION_SERVICE);
}
} catch (NotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
}
private void messageNotification(Context context, Intent intent) {
/* try {
Date date = new Date();
int notification_id = (int) date.getTime();
if(intent.getExtras()!=null){
Bundle message = intent.getExtras();
String s= message.getString("the_message");
JSONObject strObj=new JSONObject(s);
Log.d("Json", strObj.toString());
String mText=strObj.get("text").toString();
String mUrl=strObj.get("imageurl").toString();
int mUrlType=strObj.getInt("imagetype");
final Intent emptyIntent = new Intent(context,ActMain.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, notification_id, emptyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.notification_logo)
.setContentTitle(context.getResources().getString(R.string.screenname_apptitle))
.setContentText(mText)
.setAutoCancel(true)
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(mText))
.setContentIntent(pendingIntent);
// Set Vibrate, Sound and Light
int defaults = 0;
defaults = defaults | Notification.DEFAULT_SOUND | Notification.FLAG_AUTO_CANCEL;
mBuilder.setDefaults(defaults);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(notification_id, mBuilder.build());
*//*Toast.makeText(context.getApplicationContext(),
"\n message : " + message, 1).show();*//*
NotificationManager objNotfManager = (NotificationManager) context
.getApplicationContext().getSystemService(
Context.NOTIFICATION_SERVICE);
}
} catch (NotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
}
private void imageNotification(Context context) {
//new LongOperation(context).execute("");
}
/*
private class LongOperation extends AsyncTask<String, Void, String> {
private Context mContext;
String url;
public LongOperation(Context context) {
mContext = context;
url=finalImg;
}
@Override
protected String doInBackground(String... params) {
message_bitmap = AirBopImageDownloader.downloadBitmap(url);
return "Executed";
}
@Override
protected void onPostExecute(String result) {
int icon = R.drawable.notification_logo;
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager)
mContext.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = null;
if ((url == null) || (url.equals(""))) {
//just bring up the app
notificationIntent = new Intent(mContext, ActMain.class);
} else {
//Launch the URL
notificationIntent = new Intent(Intent.ACTION_VIEW);
notificationIntent.setData(Uri.parse(url));
notificationIntent.addCategory(Intent.CATEGORY_BROWSABLE);
}
// set intent so it does not start a new activity
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent =
PendingIntent.getActivity(mContext, 0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(mContext)
.setContentTitle(mContext.getResources().getString(R.string.screenname_apptitle))
.setContentText(mText)
.setContentIntent(intent)
.setSmallIcon(icon)
.setWhen(when)
.setStyle(new NotificationCompat.BigPictureStyle()
.bigPicture(message_bitmap))
.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, notification);
}
@Override
protected void onPreExecute() {}
@Override
protected void onProgressUpdate(Void... values) {}*/
}
//////////////////////////////////////////////////////////////////////////////////////////////////////
`GCMNotificationIntentService.java`
import android.app.IntentService;
import android.app.NotificationManager;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.NotificationCompat;
import com.google.android.gms.gcm.GoogleCloudMessaging;
/**
* Created by Devrath on 10-05-2016.
*/
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 on server: "+ extras.toString());
} else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
//sendNotification("Message Received from Google GCM Server: "+ extras.get(Keys.MSG_KEY));
}
}
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
}
//////////////////////////////////////////////////////////////////////////////////////////
`In Manifest`
<!-- GCM -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="com.traktion.doctor.permission.C2D_MESSAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<permission
android:name="com.traktion.doctor.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<!-- GCM -->
`and inside application`
</application>
<!-- GCM -->
<receiver
android:name="com.traktion.doctor.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.traktion.doctor.Gcm" />
</intent-filter>
</receiver>
<service android:name=".GcmIntentService" />
<!-- GCM -->
</application>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment