azureのNotification Hubsを使用してpush通知を送信することになったので備忘録。
サーバ側の開発です。(スマホアプリはわかりません。)
Java SDK入手
ここからJava SDKを入手
一応公式サイトとのことです。
コンパイルとビルド
mavenコマンドを使用するので、mavenインストールしていない場合はここを参照
pom.xmlがあるフォルダでmavenコマンドを実行するだけ
cd NotificationHubs
mvn package
そうするとtarget配下にNotification-Hubs-java-sdk-0.1.0.jarできます。
これをパスが通ったフォルダに置いてください。
使い方
タグを指定して送信することを想定しています。
事前にトークンとタグをNotification Hubsに登録していることが前提です。
トークンはメールアドレスみたいなイメージで
タグはメールアドレスみたいなイメージです。
タグを指定してpush通知を送信すると、そのタグに紐づいているトークンすべてにpush通知を送信してくれます。
push通知送信(即時送信)
String connectionString = "Endpoint=sb://xxxxx.servicebus.windows.net/;SharedAccessKeyName=DefaultFullSharedAccessSignature;SharedAccessKey=~~~~~";
String hubPath = "Notification hubsの名前";
NotificationHub hub = new NotificationHub(connectionString, hubPath);
String message = "push通知";
String body = String.format("{\"data\":{\"message\":\"%s\"}}", message);
// android端末用
Notification notifiation = Notification.createFcmNotifiation(body);
hub.sendNotification(notifiation, "タグ名");
push通知送信(日時指定送信)
String connectionString = "Endpoint=sb://xxxxx.servicebus.windows.net/;SharedAccessKeyName=DefaultFullSharedAccessSignature;SharedAccessKey=~~~~~";
String hubPath = "Notification hubsの名前";
NotificationHub hub = new NotificationHub(connectionString, hubPath);
String message = "push通知";
String body = String.format("{\"data\":{\"message\":\"%s\"}}", message);
// android端末用
Notification notifiation = Notification.createFcmNotifiation(body);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = dateFormat.parse("2020-01-01 00:00:00");
hub.scheduleNotification(notifiation, "タグ名", date);
トークンとタグの登録
事前にトークンとタグをNotification Hubsに登録していることが前提ですと記載しましたが、
サーバ側でもトークンとタグを登録できます。(トークンとタグがわかれば)
// Android端末用
Registration reg = new FcmRegistration("トークン");
reg.getTags().add("タグ名");
NotificationHub hub = new NotificationHub(connectionString, hubPath);
Registration registreg = hub.createRegistration(reg);
トークンとタグの削除
トークンとタグを削除する場合はタグを指定するか、RegistrationIdを指定します。
・タグで削除する場合は意図しないトークンも削除されるため、注意が必要です。
・RegistrationIdはトークンとタグの登録で登録結果(上のソースではregistreg )の中に詰まっています。
この値でトークンとタグを一意に識別することができます。
NotificationHub hub = new NotificationHub(connectionString, hubPath);
// タグを指定して削除
CollectionResult collectionResult = hub.getRegistrationsByTag(tag);
for (Registration registration:collectionResult.getRegistrations()) {
hub.deleteRegistration(registration.getRegistrationId());
}
// RegistrationIdを指定して削除
hub.deleteRegistration(registreg.getRegistrationId());