private void sendNotification(String message, String userId, String otherUserId) {
DatabaseReference tokensRef = FirebaseDatabase.getInstance().getReference(“FCMTokens”);
tokensRef.child(otherUserId).get().addOnCompleteListener(task -> {
if (task.isSuccessful() && task.getResult().exists()) {
String token = task.getResult().getValue(String.class);
if (token != null) {
new Thread(() -> {
try {
String accessToken = AccessToken.getAccessToken();
if (accessToken != null) {
sendFCMNotification(token, message, userId, accessToken);
}
} catch (Exception e) {
Log.e("sendNotification", "Failed to send notification", e);
}
}).start();
} else {
Log.e("sendNotification", "Token is null for user: " + otherUserId);
}
} else {
Log.e("sendNotification", "Failed to get token for user: " + otherUserId, task.getException());
}
});
}
private void sendFCMNotification(String token, String message, String names, String accessToken) {
try {
URL url = new URL("https://fcm.googleapis.com/v1/projects/checki-fee94/messages:send");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization", "Bearer " + accessToken);
conn.setRequestProperty("Content-Type", "application/json; UTF-8");
conn.setDoOutput(true);
JSONObject json = new JSONObject();
JSONObject messageJson = new JSONObject();
messageJson.put("token", token);
// Add type information to data payload
JSONObject data = new JSONObject();
data.put("type", "message");
JSONObject notification = new JSONObject();
notification.put("title", "New Message from " + names);
notification.put("body", message);
messageJson.put("notification", notification);
json.put("message", messageJson);
try (OutputStream os = conn.getOutputStream()) {
byte[] input = json.toString().getBytes("utf-8");
os.write(input, 0, input.length);
}
int responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
Log.d("sendFCMNotification", "Notification sent successfully");
} else {
Log.e("sendFCMNotification", "Failed to send notification. Response code: " + responseCode);
}
} catch (IOException | JSONException e) {
Log.e("sendFCMNotification", "Error sending notification", e);
}
}
Tying to send notification using HTTP v1 the tokens are already saved in the database.
THROWING THIS ERROR Failed to send notification. Response code: 400
New contributor
moses mutiso is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1