This is mobile era. Most of portal have it's own mobile app. Many time we have situation to access portal data from mobile app using web services. Also need to notify mobile user by notification after processing request successfull. I spend more then a day to find the api and implement to achive this requirement. So here i am sharing how we can send mobile notification from java.
public static Response sendAndroidNotification(String deviceToken,String message,String title) {
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/json");
JSONObject obj = new JSONObject();
JSONObject msgObject = new JSONObject();
msgObject.put("body", message);
msgObject.put("title", title);
// msgObject.put("icon", ANDROID_NOTIFICATION_ICON);
msgObject.put("color", "#ff0000");
obj.put("to", deviceToken);
obj.put("notification",msgObject);
RequestBody body = RequestBody.create(mediaType, obj.toString());
Request request = new Request.Builder().url(FIRE_BASE_SERVER_URL).post(body)
.addHeader("Content-Type", "application/json")
.addHeader("Authorization", "key="+SERVER_KEY).build();
Response response;
try {
response = client.newCall(request).execute();
_log.info( "Response : " + response.body().string());
return response;
} catch (IOException e) {
_log.info(e.getMessage(),e);
}
return null;
}
Note:
FIRE_BASE_SERVER_URL = https://fcm.googleapis.com/fcm/send
SERVER_KEY = Your app server key. you can find it from firebase portal.
deviceToken = Your deviceId is generate when you install app. you can find it from firebase portal.
This is very simple implementation to send notification to mobile device using java.
HTH!!
Thank you,
Ketan Savaliya