Skip to content

Instantly share code, notes, and snippets.

@ChrisRisner
Last active August 29, 2015 14:06
Show Gist options
  • Save ChrisRisner/0bb1f83917cdf4c35dea to your computer and use it in GitHub Desktop.
Save ChrisRisner/0bb1f83917cdf4c35dea to your computer and use it in GitHub Desktop.
Android Push Notifications with Notification Hubs
exports.get = function(request, response) {
var azure = require('azure');
var notificationHubService = azure.createNotificationHubService('NotificationHubName',
'NotificationHubFullSharedAccessSignature');
notificationHubService.gcm.send(null,
'{"data":{"msg" : "Hello from Mobile Services!"}}'
,
function (error)
{
if (!error) {
console.warn("Notification successful");
}
}
);
response.send(statusCodes.OK, { message : 'Notification Sent' });
};
<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.INTERNET"/>
<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" />
<permission android:name="PACAKGE.permission.C2D_MESSAGE" android:protectionLevel="signature" />
<uses-permission android:name="PACKAGE.permission.C2D_MESSAGE"/>
<receiver android:name="com.microsoft.windowsazure.notifications.NotificationsBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="PACKAGE" />
</intent-filter>
</receiver>
public class MyHandler extends NotificationsHandler {
public static final int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
Context ctx;
@Override
public void onReceive(Context context, Bundle bundle) {
ctx = context;
String nhMessage = bundle.getString("msg");
sendNotification(nhMessage);
}
private void sendNotification(String msg) {
mNotificationManager = (NotificationManager)
ctx.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(ctx, 0,
new Intent(ctx, MainActivity.class), 0);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(ctx)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Notification Hub Demo")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.setContentText(msg);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(ctx, msg, duration);
toast.show();
}
}
mGcm = GoogleCloudMessaging.getInstance(getActivity());
String connectionString = "NotificationHubListenSharedAccessSignature";
mHub = new NotificationHub("NotificationHubName", connectionString, getActivity());
NotificationsManager.handleNotifications(getActivity(), SENDER_ID, MyHandler.class);
@SuppressWarnings("unchecked")
private void registerWithGcm() {
new AsyncTask() {
@Override
protected Object doInBackground(Object... params) {
try {
mRegistrationId = mGcm.register(SENDER_ID);
Log.i(TAG, "Registered with id: " + mRegistrationId);
} catch (Exception e) {
return e;
}
return null;
}
protected void onPostExecute(Object result) {
lblRegistration.setText(mRegistrationId);
lblStatus.setText(getResources().getString(R.string.status_registered));
};
}.execute(null, null, null);
}
private OnClickListener registerWithNoTags = new OnClickListener() {
@SuppressWarnings("unchecked")
@Override
public void onClick(View v) {
Log.i(TAG, "Tapped register with no tags");
new AsyncTask() {
@Override
protected Object doInBackground(Object... params) {
try {
mHub.register(mRegistrationId);
} catch (Exception e) {
Log.e(TAG, "Issue registering with hub: " + e.getMessage());
return e;
}
return null;
}
protected void onPostExecute(Object result) {
lblStatus.setText(getResources().getString(R.string.status_registered_with_no_tags));
};
}.execute(null, null, null);
}
};
private OnClickListener registerWithTags = new OnClickListener() {
@SuppressWarnings("unchecked")
@Override
public void onClick(View v) {
Log.i(TAG, "Tapped register with tags");
new AsyncTask() {
@Override
protected Object doInBackground(Object... params) {
try {
mHub.register(mRegistrationId, "MyTag", "AndroidUser", "AllUsers");
} catch (Exception e) {
Log.e(TAG, "Issue registering with hub with tag: " + e.getMessage());
return e;
}
return null;
}
protected void onPostExecute(Object result) {
lblStatus.setText(getResources().getString(R.string.status_registered_with_tags));
};
}.execute(null, null, null);
}
};
private OnClickListener registerWithTemplates = new OnClickListener() {
@SuppressWarnings("unchecked")
@Override
public void onClick(View v) {
Log.i(TAG, "Tapped register with templates");
new AsyncTask() {
@Override
protected Object doInBackground(Object... params) {
try {
mHub.registerTemplate(mRegistrationId, "messageTemplate",
"{\"data\":{\"msg\":\"$(message)\"}, \"collapse_key\":\"$(collapse_key)\"}",
"MyTag", "AllUsers", "AndroidUser");
} catch (Exception e) {
Log.e(TAG, "Issue registering with hub with template: " + e.getMessage());
return e;
}
return null;
}
protected void onPostExecute(Object result) {
lblStatus.setText(getResources().getString(R.string.status_registered_with_templates));
};
}.execute(null, null, null);
}
};
exports.get = function(request, response) {
var azure = require('azure');
var notificationHubService = azure.createNotificationHubService('NotificationHubName',
'NotificationHubFullSharedAccessSignature');
notificationHubService.gcm.send('MyTag',
'{"data":{"msg" : "Hello MyTag!"}}'
,
function (error)
{
if (!error) {
console.warn("Notification successful");
}
}
);
response.send(statusCodes.OK, { message : 'Notification Sent' });
};
exports.get = function(request, response) {
var azure = require('azure');
var notificationHubService = azure.createNotificationHubService('NotificationHubName',
'NotificationHubFullSharedAccessSignature');
var payload = '{ "message" : "Template push to everyone!", "collapse_key" : "Message" }';
notificationHubService.send(null, payload,
function(error, outcome) {
console.log('issue sending push');
console.log('error: ', error);
console.log('outcome: ',outcome);
});
response.send(statusCodes.OK, { message : 'Notification Sent' });
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment