Firebase cloud messaging to send push Notifications
Posted By : Krishna Verma | 23-Sep-2018
In this blog, I will show you how you can send the Push notification to your users on their mobile phone using the Firebase cloud messaging. As in any mobile application like WhatsApp, hike, Paytm and
Like in Facebook Messenger when you are using facebook messenger and you are chatting with someone you get to know when someone sends you a message and you can easily chat with them, but what happens if your phone is idle and you are not using that, and someone sends you a message if push notifications are not enabled then you will not get to know about that message instantly, you have to open the messenger then you get to know that you have received a message. But if Push notifications are enabled you get a notification with the notification sound that you have received a message from the sender name.so you can understand the importance of the push notifications.
I Will show you how you can interact with firebase using java application to send a notification to users. To implement Firebase in java you need two things Firebase API URL and Firebase-Server Key.you can find the firebase API URL on the official site of firebase cloud messaging and for firebase server Key The Mobile App developer will provide you that key. Now the big point is How to send messages to the user.
here is the code in spring-boot:
public class FirebaseService { private static Logger logger = LoggerFactory.getLogger(FirebaseService.class); @Autowired private FirebaseRepository firebaseRepository; @Value("${firebase.api.url}") private String firebaseApiUrl; @Value("${firebase.server.key}") private String firebaseServerKey; @KafkaListener(topicPartitions = @TopicPartition(topic = DataConstants.KAFKA_NOTIFICATION_TOPIC, partitions = { "0" })) public void sendPushNotification(ConsumerRecordconsumerRecord) throws IOException { FirebaseDTO firebaseDTO = ObjectSerializer.getObject(consumerRecord.value(), FirebaseDTO.class); if (firebaseDTO.getDeviceToken() == null || firebaseDTO.getDeviceType() == null || firebaseDTO.getMessage() == null || firebaseDTO.getNotificationType() == null || firebaseDTO.getUserId() == null) { logger.info("required data is missing"); } else { URL url = new URL(firebaseApiUrl); HttpURLConnection conn = makeHttpConnection(url); JSONObject json = new JSONObject(); Map userUpdates = new HashMap<>(); userUpdates.put(DataConstants.TITTLE, firebaseDTO.getNotificationType()); try { setDataInJson(json, userUpdates, firebaseDTO); } catch (Exception ex) { logger.error(ex.getMessage()); ex.printStackTrace(); } String firebaseMessage = ""; try { logger.info("json data is : {}", json); // firebaseMessage = sendMessageToFirebase(conn, json); } catch (Exception ex) { logger.error(ex.getMessage()); ex.printStackTrace(); } if (firebaseMessage.contains("message_id")) { logger.info("GCM Notification is sent successfully"); } else { logger.info("GCM Notification sending failed"); } Firebase firebase = new Firebase(); firebase.setRead(false); firebase.setUserId(firebaseDTO.getUserId()); firebase.setMessage(firebaseDTO.getMessage()); firebase.setNotificationType(firebaseDTO.getNotificationType()); firebase.setDeliveryStatus("success"); firebase.setDeviceType(firebaseDTO.getDeviceType()); Date date = new Date(); firebase.setMessageDate(date); firebaseRepository.save(firebase); } } /** * krishna 05-Sep-2018 */ public String sendMessageToFirebase(HttpURLConnection conn, JSONObject json) { String message = ""; try { OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(json.toString()); wr.flush(); BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); logger.info("buffer reader is :{}", br); String output; while ((output = br.readLine()) != null) { logger.info("notification : {}", output); message = output; } } catch (Exception e) { e.printStackTrace(); } return message; } /** * krishna 05-Sep-2018 */ public void setDataInJson(JSONObject json, Map userUpdates, FirebaseDTO firebaseDTO) { try { logger.info("device-type: {}", firebaseDTO.getDeviceType()); logger.info("device-token: {}", firebaseDTO.getDeviceToken()); json.put("to", firebaseDTO.getDeviceToken().trim()); if (firebaseDTO.getDeviceType().equals(DeviceType.IOS)) { logger.info("IOS:-"); userUpdates.put("body", firebaseDTO.getMessage()); json.put("notification", userUpdates); json.put("priority", "high"); } else if (firebaseDTO.getDeviceType().equals(DeviceType.ANDROID)) { logger.info("android:-"); userUpdates.put("message", firebaseDTO.getMessage()); json.put("data", userUpdates); } else { logger.info("not android and ios:-"); userUpdates.put("message", firebaseDTO.getMessage()); json.put("data", userUpdates); } } catch (JSONException e1) { e1.printStackTrace(); } } /** * krishna 05-Sep-2018 */ public HttpURLConnection makeHttpConnection(URL url) { HttpURLConnection conn = null; try { conn = (HttpURLConnection) url.openConnection(); conn.setUseCaches(false); conn.setDoInput(true); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Authorization", "key=" + firebaseServerKey); conn.setRequestProperty("Content-Type", "application/json"); } catch (Exception ex) { logger.error(ex.getMessage()); ex.printStackTrace(); } return conn; } }
#####Firebase DTO #######
public class FirebaseDTO {
@NotNull
private String deviceToken;
@NotNull
private String message;
@NotNull
private DeviceType deviceType;
@NotNull
private NotificationType notificationType;
@NotNull
private Long userId;
/**
* @return the deviceToken
*/
public String getDeviceToken() {
return deviceToken;
}
/**
* @param deviceToken
* the deviceToken to set
*/
public void setDeviceToken(String deviceToken) {
this.deviceToken = deviceToken;
}
/**
* @return the message
*/
public String getMessage() {
return message;
}
/**
* @param message
* the message to set
*/
public void setMessage(String message) {
this.message = message;
}
/**
* @return the deviceType
*/
public DeviceType getDeviceType() {
return deviceType;
}
/**
* @param deviceType
* the deviceType to set
*/
public void setDeviceType(DeviceType deviceType) {
this.deviceType = deviceType;
}
/**
* @return the notificationType
*/
public NotificationType getNotificationType() {
return notificationType;
}
/**
* @param notificationType
* the notificationType to set
*/
public void setNotificationType(NotificationType notificationType) {
this.notificationType = notificationType;
}
/**
* @return the userId
*/
public Long getUserId() {
return userId;
}
/**
* @param userId the userId to set
*/
public void setUserId(Long userId) {
this.userId = userId;
}
}
here Device Token is the unique Mobile Token which is provided to you by the mobile application Developer.
Thanks
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Krishna Verma
Krishna is a Software Developer having key skills in java , his hobbies are learning new technologies