Skip to content

Instantly share code, notes, and snippets.

@domadev812
Forked from ToeJamson/1.xml
Last active November 15, 2017 21:05
Show Gist options
  • Save domadev812/d54b71ed7942fb29ba392c3363c2b569 to your computer and use it in GitHub Desktop.
Save domadev812/d54b71ed7942fb29ba392c3363c2b569 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" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
PNConfiguration pnConfiguration = new PNConfiguration();
pnConfiguration.setSubscribeKey("demo");
pnConfiguration.setPublishKey("demo");
PubNub pubnub = new PubNub(pnConfiguration);
private void sendRegistrationId(String regId) {
pubnub.addPushNotificationsOnChannels()
.pushType(PNPushType.GCM)
.channels(Arrays.asList("ch1", "ch2", "ch3"))
.deviceId(regId)
.async(new PNCallback<PNPushAddChannelResult>() {
@Override
public void onResponse(PNPushAddChannelResult result, PNStatus status) {
// handle response.
}
});
}
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 {
pubnub.removePushNotificationsFromChannels()
.deviceId("googleDevice")
.channels(Arrays.asList("ch1", "ch2", "ch3"))
.pushType(PNPushType.GCM)
.async(new PNCallback<PNPushRemoveChannelResult>() {
@Override
public void onResponse(PNPushRemoveChannelResult result, PNStatus status) {
}
});
}
<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);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment