Skip to content

Instantly share code, notes, and snippets.

@billmote
Last active August 29, 2015 14:08
Show Gist options
  • Save billmote/0651634044dbdcdf520f to your computer and use it in GitHub Desktop.
Save billmote/0651634044dbdcdf520f to your computer and use it in GitHub Desktop.
Simple GCM Implementation
<!-- GCM permissions -->
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.VIBRATE" />
<permission
android:name="com.example.android.app.gcm.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.example.android.app.gcm.permission.C2D_MESSAGE" />
<!-- GCM permissions -->
<!-- Inside Application TAG GCM -->
<receiver
android:name=".gcm.GCMReceiver"
android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="com.example.android.app" />
</intent-filter>
</receiver>
<service android:name=".gcm.GCMService" />
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
<!-- GCM -->
<!-- GCM -->
<string name="gcm_project_number">123456789098</string>
public class GCMReceiver extends WakefulBroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
ComponentName comp = new ComponentName(context.getPackageName(),GCMService.class.getName());
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
public class GCMService extends IntentService implements SaveAudioMessageTask.SaveAudioMessageListener {
private static final String TAG = GCMService.class.getSimpleName();
public static final String KEY_EXTRAS_ACTION_RECEIVED_AUDIO_MESSAGE = "audioMessage";
private AudioMessage receivedAudioMessage;
private ActionType action;
private enum ActionType { NEW_AUDIO_MESSAGE }
@DebugLog
public GCMService() {
super("FoundationGCMService");
}
@DebugLog
@Override
protected void onHandleIntent(Intent intent) {
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
Bundle extras = intent.getExtras();
if (!extras.isEmpty()) {
Gson jsonParser = FoundationAPIBuilder.buildJsonParser();
if (extras.containsKey(KEY_EXTRAS_ACTION_RECEIVED_AUDIO_MESSAGE)) {
action = ActionType.NEW_AUDIO_MESSAGE;
Log.i(TAG, "Received push, RECEIVED_AUDIO_MESSAGE");
this.receivedAudioMessage = jsonParser.fromJson(extras.getString(KEY_EXTRAS_ACTION_RECEIVED_AUDIO_MESSAGE), AudioMessage.class);
Log.v(TAG, extras.getString(KEY_EXTRAS_ACTION_RECEIVED_AUDIO_MESSAGE));
new SaveAudioMessageTask(this, true, true, -1).execute(this.receivedAudioMessage);
}
}
GCMReceiver.completeWakefulIntent(intent);
}
@DebugLog
@Override
public void onPostExecute() {
Intent resultIntent = new Intent(this, MainActivity.class);
switch (action) {
case NEW_AUDIO_MESSAGE:
resultIntent.putExtra(MainActivity.KEY_EXTRAS_START_ON_MESSAGES, true);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
Uri soundUri = Uri.parse("android.resource://" + this.getPackageName() + "/" + R.raw.notification);
String notificationBody = this.receivedAudioMessage.getFrom().getFullname() + " " + this.getResources().getString(R.string.notification_new_message_text);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(this.getResources().getString(R.string.notification_new_message_title))
.setOngoing(false)
.setContentIntent(resultPendingIntent)
.setAutoCancel(true)
.setContentText(notificationBody)
.setTicker(notificationBody)
.setDefaults(Notification.DEFAULT_VIBRATE | Notification.DEFAULT_LIGHTS);
if (SharedPreferencesHelper.getBoolean(SharedPreferencesHelper.KEY_PREFS_PLAY_NOTIFICATION_SOUNDS, true)) {
mBuilder
.setSound(soundUri);
}
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(R.id.notification_id, mBuilder.build());
break;
}
}
}
public class GCMTools {
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
public static boolean isGooglePlayAvailable(Activity act) {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(act);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, act, PLAY_SERVICES_RESOLUTION_REQUEST).show();
}
return false;
}
return true;
}
public static void registerToGCM(Activity act){
if (isGooglePlayAvailable(act)) {
UserLocalStorageHandler userDB = new UserLocalStorageHandler(act);
User currentUser = null;
try {
currentUser = userDB.getCurrentUser();
} catch (SQLException e) {
e.printStackTrace();
}
if (currentUser == null || currentUser.getGCMRegistrationId() == null || currentUser.getGCMRegistrationId().trim().isEmpty()) {
GCMRegistration regTask = new GCMRegistration(act, userDB);
regTask.execute();
}
}
}
private static class GCMRegistration extends AsyncTask{
private final Context context;
private final UserLocalStorageHandler usersDB;
public GCMRegistration(Context ctx, UserLocalStorageHandler usersDB){
super();
this.context = ctx;
this.usersDB = usersDB;
}
@Override
protected Object doInBackground(Object[] params) {
try{
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this.context);
String registrationID = gcm.register(this.context.getString(R.string.gcm_project_number));
Log.d("GCM", "Registered with regID: " + registrationID);
User gcmUpdateData = new User();
User currentUser = this.usersDB.getCurrentUser();
gcmUpdateData.setRemoteid(currentUser.getRemoteid());
gcmUpdateData.setGCMRegistrationId(registrationID);
QuikeyAPIBuilder.getApiInstance().userPut(gcmUpdateData);
currentUser.setGCMRegistrationId(registrationID);
this.usersDB.saveCurrentUser(currentUser);
} catch (IOException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (RetrofitError e){
e.printStackTrace();
}
return null;
}
}
}
// ...
@Override
protected void onResume() {
super.onResume();
// ...
GCMTools.registerToGCM(this);
// ...
}
// ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment