用户收到新消息时发送通知

时间:2020-03-06 14:15:39

标签: java android firebase-cloud-messaging

我正在尝试为我的大学项目创建一个个人聊天应用程序。我创建了一个聊天活动,用户可以在其中聊天并接收消息,现在我想向其添加通知功能,以便可以在用户收到的每条消息上通知该用户,为此,我在互联网上进行了搜索,发现FCM(Firebase云混乱)并尝试使用它不起作用。 下面是我用来向用户显示通知的代码。

  public class MyFirebaseMessagingService extends FirebaseMessagingService {

private static final String TAG = "MyFirebaseMsgService";

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    sendNotification(remoteMessage.getNotification().getBody());

    Log.d(TAG, "From: " + remoteMessage.getFrom());


    if (remoteMessage.getData().size() > 0) {
        Log.d(TAG, "Message data payload: " + remoteMessage.getData());

        if (true) {

            scheduleJob();
        } else {

            handleNow();
        }

    }


    if (remoteMessage.getNotification() != null) {
        Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
    }


}

@Override
public void onNewToken(String token) {
    Log.d(TAG, "Refreshed token: " + token);


    sendRegistrationToServer(token);
}

private void scheduleJob() {

    OneTimeWorkRequest work = new OneTimeWorkRequest.Builder(MyWorker.class)
            .build();
    WorkManager.getInstance().beginWith(work).enqueue();

}

private void handleNow() {
    Log.d(TAG, "Short lived task is done.");
}


private void sendRegistrationToServer(String token) {
    // TODO: Implement this method to send token to your app server.
}


private void sendNotification(String messageBody) {
    Intent intent = new Intent(this, personalChat.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);

    String channelId = "chat";
    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder =
            new NotificationCompat.Builder(this, channelId)
                    .setSmallIcon(R.drawable.logo)
                    .setContentTitle("Title")
                    .setContentText(messageBody)
                    .setAutoCancel(true)
                    .setSound(defaultSoundUri)
                    .setContentIntent(pendingIntent);

    NotificationManager notificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    // Since android Oreo notification channel is needed.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel channel = new NotificationChannel(channelId,
                "Channel human readable title",
                NotificationManager.IMPORTANCE_DEFAULT);
        notificationManager.createNotificationChannel(channel);
    }

    notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
 }

也许我用错了方式....帮助我,以便我可以完成我的项目

0 个答案:

没有答案