Я пытаюсь получать уведомления в своем приложении для Android с помощью Firebase Cloud Messaging (FCM). Но это не работает так, как я хочу. У меня два устройства, и я отправляю уведомления с одного на другое. Я получаю уведомления на втором устройстве. Однако, когда я нажимаю на него, он не входит в нужное мне действие. Чтобы разобраться в проблеме, когда я удерживал уведомление и просматривал настройки, я понял, что оно на самом деле не пошло на созданный мной канал уведомлений. Например, я создаю уведомление и службу с именем «Канал комментариев», но уведомление отправляется на канал с именем «Разное». Я хочу прослушать входящее уведомление.
На первом устройстве, на которое я отправлял уведомления, я добавил в данные JSON такие параметры, как click_action,channel_id, android_channel_id, но на этот раз уведомлений не было. были отправлены. Можете ли вы помочь?
// Первое устройство (для отправки уведомления)
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.execute(() -> {
GoogleCredentials googleCredentials;
try {
InputStream inputStream = getApplicationContext().getAssets().open(fcmServiceJsonPath);
googleCredentials = GoogleCredentials
.fromStream(inputStream)
.createScoped("https://www.googleapis.com/auth/firebase.messaging");
googleCredentials.refreshIfExpired();
AccessToken token = googleCredentials.getAccessToken();
if (token == null) {
return;
}
String tokenValue = token.getTokenValue();
try {
OkHttpClient client = new OkHttpClient();
// Notification payload
JSONObject notification = new JSONObject();
notification.put("title", title);
notification.put("body", body);
//notification.put("channel_id", "post_comment");
// If I enable this, the notification goes away, it gives a 404 error.
JSONObject data = new JSONObject();
data.put("title", title);
data.put("body", body);
data.put("notification_id", String.valueOf(notification_id));
data.put("post_id", String.valueOf(getPostId));
data.put("comment_id", String.valueOf(inserted_comment_id));
data.put("top_comment_id", String.valueOf(inserted_top_comment_id));
data.put("comment_count", String.valueOf(comments_size));
data.put("post_owner_user_id", String.valueOf(getPostOwnerUserId));
data.put("post_owner_username", String.valueOf(getPostOwnerUsername));
data.put("inserted_db", is_reply_comment ? "sub_comment" : "comment");
data.put("timestamp", String.valueOf(System.currentTimeMillis()));
// Request payload
JSONObject message = new JSONObject();
message.put("token", fcmToken);
message.put("notification", notification);
message.put("data", data);
// message.put("android", new JSONObject().put("priority", "high"));
//JSONObject androidPayload = new JSONObject();
//JSONObject notificationPayload = new JSONObject();
//notificationPayload.put("click_action", "post_comment");
//notificationPayload.put("channel_id", "Yorum Bildirimi");
//androidPayload.put("notification", notificationPayload);
//message.put("android", androidPayload);
// message.put("click_action", ".activity.PostCommentActivity");
JSONObject requestBody = new JSONObject();
requestBody.put("message", message);
RequestBody bodyRequest = RequestBody.create(
MediaType.parse("application/json; charset=utf-8"),
requestBody.toString()
);
okhttp3.Request request = new okhttp3.Request.Builder()
.url(fcmUrl)
.post(bodyRequest)
.addHeader("Authorization", "Bearer " + tokenValue)
.addHeader("Content-Type", "application/json")
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NonNull Call call, @NonNull IOException ioException) {
Log.d("TAG_EXCEPTION", "Bildirim gönderilemedi: " + ioException.getMessage());
}
@Override
public void onResponse(@NonNull Call call, @NonNull Response response) {
if (response.isSuccessful()) {
Log.d("TAG_EXCEPTION", "Notification sent successfully!");
} else {
Log.d("TAG_EXCEPTION", "Notification. Mistake: " + response);
}
}
});
} catch (JSONException e) {
Log.d("TAG_EXCEPTION", "JSON Ex: " + e.getMessage());
}
} catch (IOException e) {
Log.d("TAG_EXCEPTION", "Service JSON Ex: " + e.getMessage());
}
});
// Второе устройство (для получения уведомлений)
// Manifest
// FCM Service
public class FCMService extends FirebaseMessagingService {
private static final String TAG = "TAG_COMMENT_FCM";
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(TAG, "RemoteMessage Running"+"getFrom: "+remoteMessage.getFrom());
if (remoteMessage.getNotification() != null) {
sendNotification(remoteMessage);
}
}
@Override
public void onNewToken(@NonNull String token) {
Log.d(TAG, "Refreshed token: " + token);
}
public void sendNotification(RemoteMessage remoteMessage) {
String messageTitle =remoteMessage.getData().get("title");
String messageBody = remoteMessage.getData().get("body");
String postIdStr = remoteMessage.getData().get("post_id");
String commentIdStr = remoteMessage.getData().get("comment_id");
String timestamp = remoteMessage.getData().get("timestamp");
int postId = postIdStr != null ? Integer.parseInt(postIdStr) : 0;
int commentId = commentIdStr != null ? Integer.parseInt(commentIdStr) : -1;
Intent intent = new Intent(this, PostCommentActivity.class);
intent.putExtra("notification_type", "fcm");
intent.putExtra("post_id", postId);
intent.putExtra("comment_id", commentId);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
Toast.makeText(getApplicationContext(), "notif", Toast.LENGTH_SHORT).show();
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
SharedPreferencesReceiver.setCommunityNotification(getApplicationContext(), true);
PendingIntent pendingIntent = PendingIntent.getActivity(this, commentId, intent, PendingIntent.FLAG_IMMUTABLE);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(getString(R.string.fcm_comment_channel),
getString(R.string.fcm_comment_channel),
NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription(getString(R.string.fcm_comment_channel));
channel.setImportance(NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, getString(R.string.fcm_comment_channel))
.setSmallIcon(R.drawable.ic_notification_icon)
.setChannelId(getString(R.string.fcm_comment_channel))
.setContentTitle(messageTitle)
.setContentText(messageBody)
.setAutoCancel(true)
.setColor(ContextCompat.getColor(this, R.color.colorPrimaryContainer))
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND)
.setContentInfo("Info")
.setContentIntent(pendingIntent)
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(messageBody));
notificationManager.notify(commentId, notificationBuilder.build());
}
}
JSONObject androidPayload = new JSONObject();
JSONObject notificationPayload = new JSONObject();
//notificationPayload.put("click_action", "post_comment");
notificationPayload.put("channel_id", "post_comment");
androidPayload.put("notification", notificationPayload);
message.put("android", androidPayload);
Подробнее здесь: https://stackoverflow.com/questions/791 ... in-android
Как я могу получать уведомления с помощью Firebase Cloud Messaging на Android? ⇐ Android
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Как я могу получать уведомления с помощью Firebase Cloud Messaging на Android?
Anonymous » » в форуме JAVA - 0 Ответы
- 9 Просмотры
-
Последнее сообщение Anonymous
-
-
-
Как я могу отправить уведомление Firebase Cloud Messaging без использования консоли Firebase?
Anonymous » » в форуме Php - 0 Ответы
- 20 Просмотры
-
Последнее сообщение Anonymous
-