Skip to content

Instantly share code, notes, and snippets.

@ToeJamson
Last active October 16, 2017 22:31
Show Gist options
  • Save ToeJamson/c63365ca3da68b3cc94f to your computer and use it in GitHub Desktop.
Save ToeJamson/c63365ca3da68b3cc94f to your computer and use it in GitHub Desktop.
android push notification intro tutorial
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<permission android:name="your.package.name.permission.C2D_MESSAGE" android:protectionLevel="signature" />
<uses-permission android:name="your.package.name.permission.C2D_MESSAGE" />
private final Pubnub pubnub = new Pubnub("demo-36" /* replace with your publish key */,
"demo-36" /* replace with your subscribe key */);
private void sendRegistrationId(String regId) {
pubnub.enablePushNotificationsOnChannel(
"your channel name",
regId);
}
private void storeRegistrationId(Context context, String regId) throws Exception {
final SharedPreferences prefs =
getSharedPreferences(MainActivity.class.getSimpleName(), Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(PROPERTY_REG_ID, regId);
editor.apply();
public void sendNotification() {
PnGcmMessage gcmMessage = new PnGcmMessage();
JSONObject jso = new JSONObject();
try {
jso.put("GCMSays", "hi");
} catch (JSONException e) { }
gcmMessage.setData(jso);
PnMessage message = new PnMessage(
pubnub,
"your channel name",
callback,
gcmMessage);
try {
message.publish();
} catch (PubnubException e) {
e.printStackTrace();
}
}
public static Callback callback = new Callback() {
@Override
public void successCallback(String channel, Object message) {
Log.i(TAG, "Success on Channel " + CHANNEL + " : " + message);
}
@Override
public void errorCallback(String channel, PubnubError error) {
Log.i(TAG, "Error On Channel " + CHANNEL + " : " + error);
}
};
private void unregister() {
new AsyncTask() {
@Override
protected Object doInBackground(Object[] params) {
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(context);
}
// Unregister from GCM
gcm.unregister();
// Remove Registration ID from memory
removeRegistrationId(context);
// Disable Push Notification
pubnub.disablePushNotificationsOnChannel("your channel name", regId);
} catch (Exception e) { }
return null;
}
}.execute(null, null, null);
}
private void removeRegistrationId(Context context) throws Exception {
final SharedPreferences prefs =
getSharedPreferences(MainActivity.class.getSimpleName(), Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.remove(PROPERTY_REG_ID);
editor.apply();
}
<receiver
android:name=".GcmBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="your.package.name" />
</intent-filter>
</receiver>
<service android:name=".GcmIntentService" />
<meta-data android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
ComponentName comp = new ComponentName(context.getPackageName(),
GcmIntentService.class.getName());
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
public class GcmIntentService extends IntentService {
public GcmIntentService() {
super("GcmIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
String messageType = gcm.getMessageType(intent);
if (!extras.isEmpty() && GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
sendNotification("Received: " + extras.toString());
}
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
private void sendNotification(String msg) {
NotificationManager 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.ic_launcher)
.setContentTitle("PubNub GCM Notification")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.setContentText(msg);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
private void register() {
if (checkPlayServices()) {
gcm = GoogleCloudMessaging.getInstance(this);
try {
regId = getRegistrationId(context);
} catch (Exception e) {
e.printStackTrace();
}
if (regId.isEmpty()) {
registerInBackground();
} else {
toastUser("Registration ID already exists: " + regId);
}
} else {
Log.e(TAG, "No valid Google Play Services APK found.");
}
}
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, this, PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Log.e(TAG, "This device is not supported.");
finish();
}
return false;
}
return true;
}
private String getRegistrationId(Context context) throws Exception {
final SharedPreferences prefs =
getSharedPreferences(MainActivity.class.getSimpleName(), Context.MODE_PRIVATE);
String registrationId = prefs.getString(PROPERTY_REG_ID, "");
if (registrationId.isEmpty()) {
return "";
}
return registrationId;
}
private void registerInBackground() {
new AsyncTask() {
@Override
protected String doInBackground(Object[] params) {
String msg;
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(context);
}
regId = gcm.register(SENDER_ID);
msg = "Device registered, registration ID: " + regId;
sendRegistrationId(regId);
storeRegistrationId(context, regId);
Log.i(TAG, msg);
} catch (Exception ex) {
msg = "Error :" + ex.getMessage();
Log.e(TAG, msg);
}
return msg;
}
}.execute(null, null, null);
}
@GleasonK
Copy link

String messageType = gcm.getMessageType(intent);
if (!extras.isEmpty() && GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE) {      
    sendNotification("Received: " + extras.toString()); 
}

needs to be

String messageType = gcm.getMessageType(intent);
if (!extras.isEmpty() && GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {      
    sendNotification("Received: " + extras.toString()); 
}

GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)

GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE is a string alone, not a boolean.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment