我需要 PendingIntent 根据用户收到的通知类型打开不同的 Activity。

huangapple go评论92阅读模式
英文:

I need for the PendingIntent to open up different Activities depending on the type of notification that the user receives

问题

当用户收到来自另一个用户的消息时他们会从```Firebase Cloud Messaging```系统收到通知当用户点击该通知时会进入```MessageActivity```,这非常好

我还有其他情况用户会收到这些```Firebase Cloud Messaging```通知当有人评论您的帖子喜欢您的帖子等当他们收到这些通知时显然应该进入```PostActivity```,而不是```MessageActivity```。

那么我是应该编写另一个```"MyFirebaseInstanceServiceActivity"```,还是可以简单地进行一些更改以便如果是评论通知则将您带到```PostActivity```,而不是```MessageActivity```?

**MyFirebaseInstanceService**

    public class MyFirebaseInstanceService extends FirebaseMessagingService {
    
        @Override
        public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
            super.onMessageReceived(remoteMessage);
    
            String sented = remoteMessage.getData().get("sented");
    
            FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
    
            if (firebaseUser != null && sented.equals(firebaseUser.getUid())) {
                sendNotification(remoteMessage);
            }
        }
    
        private void sendNotification(RemoteMessage remoteMessage) {
            String user = remoteMessage.getData().get("user");
            String icon = remoteMessage.getData().get("icon");
            String title = remoteMessage.getData().get("title");
            String body = remoteMessage.getData().get("body");
    
            RemoteMessage.Notification notification = remoteMessage.getNotification();
            int j = Integer.parseInt(user.replaceAll("[\\D]", ""));
            Intent intent = new Intent(MyFirebaseInstanceService.this, MessageActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString("id", user);
            intent.putExtras(bundle);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            PendingIntent pendingIntent = PendingIntent.getActivity(MyFirebaseInstanceService.this, j, intent, PendingIntent.FLAG_ONE_SHOT);
    
            Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            NotificationCompat.Builder builder = new NotificationCompat.Builder(MyFirebaseInstanceService.this, NOTIFICATION_CHANNEL_ID);
            builder.setSmallIcon(R.drawable.ic_notification_events);
            builder.setContentTitle(title);
            builder.setContentText(body);
            builder.setAutoCancel(true);
            builder.setSound(sound);
            builder.setContentIntent(pendingIntent);
    
            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, NOTIFICATION_CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
                notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
                notificationChannel.enableVibration(true);
                notificationChannel.setLightColor(Color.BLUE);
                notificationManager.createNotificationChannel(notificationChannel);
            }
    
            int i = 0;
            if (j > 0)
                i = j;
    
            notificationManager.notify(i, builder.build());
        }
    
        @Override
        public void onNewToken(@NonNull String s) {
            super.onNewToken(s);
            Log.d("TOKEN", s);
    
            Task<InstanceIdResult> task = FirebaseInstanceId.getInstance().getInstanceId();
            task.addOnSuccessListener(instanceIdResult -> {
                if (task.isSuccessful()) {
                    String token = task.getResult().getToken();
                    sendRegistrationToServer(token);
                    Log.d("TOKEN", token);
                }
            });
    
            task.addOnFailureListener(e -> {
                if (!task.isSuccessful()) {
                    Exception exception = task.getException();
                    Log.d("TOKEN", exception.getMessage());
                }
            });
        }
    
        private void sendRegistrationToServer(String token) {
            FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
            if (firebaseUser != null) {
                DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Tokens");
                Token token1 = new Token(token);
                reference.child(firebaseUser.getUid()).setValue(token1);
            }
        }
    }
英文:

When a user receives a message from another user they get a notification from the Firebase Cloud Messaging system. When the user clicks on that notification, it takes them to the MessageActivity which is great.

I have a few other instances where a user receives one of these Firebase Cloud Messaging notifications: when someone comments on your posts, likes your post, etc. When they receives those notifications obviously it should take them to the PostActivity, and not the MessageActivity.

So, should I write another "MyFirebaseInstanceServiceActivity" or can I just do some simple change so that if it's a comment notification it takes you to the PostActivity instead of the MessageActivity?

MyFirebaseInstanceService

public class MyFirebaseInstanceService extends FirebaseMessagingService {
@Override
public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
String sented = remoteMessage.getData().get("sented");
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
if (firebaseUser != null && sented.equals(firebaseUser.getUid())) {
sendNotification(remoteMessage);
}
}
private void sendNotification(RemoteMessage remoteMessage) {
String user = remoteMessage.getData().get("user");
String icon = remoteMessage.getData().get("icon");
String title = remoteMessage.getData().get("title");
String body = remoteMessage.getData().get("body");
RemoteMessage.Notification notification = remoteMessage.getNotification();
int j = Integer.parseInt(user.replaceAll("[\\D]", ""));
Intent intent = new Intent(MyFirebaseInstanceService.this, MessageActivity.class);
Bundle bundle = new Bundle();
bundle.putString("id", user);
intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(MyFirebaseInstanceService.this, j, intent, PendingIntent.FLAG_ONE_SHOT);
Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder builder = new NotificationCompat.Builder(MyFirebaseInstanceService.this, NOTIFICATION_CHANNEL_ID);
builder.setSmallIcon(R.drawable.ic_notification_events);
builder.setContentTitle(title);
builder.setContentText(body);
builder.setAutoCancel(true);
builder.setSound(sound);
builder.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, NOTIFICATION_CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
notificationChannel.enableVibration(true);
notificationChannel.setLightColor(Color.BLUE);
notificationManager.createNotificationChannel(notificationChannel);
}
int i = 0;
if (j > 0)
i = j;
notificationManager.notify(i, builder.build());
}
@Override
public void onNewToken(@NonNull String s) {
super.onNewToken(s);
Log.d("TOKEN", s);
Task<InstanceIdResult> task = FirebaseInstanceId.getInstance().getInstanceId();
task.addOnSuccessListener(instanceIdResult -> {
if (task.isSuccessful()) {
String token = task.getResult().getToken();
sendRegistrationToServer(token);
Log.d("TOKEN", token);
}
});
task.addOnFailureListener(e -> {
if (!task.isSuccessful()) {
Exception exception = task.getException();
Log.d("TOKEN", exception.getMessage());
}
});
}
private void sendRegistrationToServer(String token) {
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
if (firebaseUser != null) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Tokens");
Token token1 = new Token(token);
reference.child(firebaseUser.getUid()).setValue(token1);
}
}
}

答案1

得分: 1

以下是您要翻译的内容:

只需进行简单的检查即可,您需要发送一些数据进行检查,以了解通知是来自评论、点赞、帖子还是其他内容。

private void sendNotification(RemoteMessage remoteMessage) {
    .....
    String user = remoteMessage.getData().get("user");
    String nType = remoteMessage.getData().get("type"); // 此处的 type 是您发送的某些数据
    int j = Integer.parseInt(user.replaceAll("\\D", ""));
    ...
    Intent intent = null;
    PendingIntent pendingIntent = null;
    Bundle bundle = new Bundle();

    if (nType.equals("message")) {
        intent = new Intent(MyFirebaseInstanceService.this, MessageActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // 在此您可以更改启动模式(launch mode)如果需要的话
        bundle.putString("id", "124"); // 在此将您的数据添加到 bundle 中
        intent.putExtras(bundle);
        pendingIntent = PendingIntent.getActivity(MyFirebaseInstanceService.this, j, intent, PendingIntent.FLAG_ONE_SHOT);
    } else if (nType.equals("comment")) {
        intent = new Intent(MyFirebaseInstanceService.this, PostActivity.class);
        bundle.putString("postId", "134"); // 在此将您的数据添加到 bundle 中
        intent.putExtras(bundle);
        // 在此,您可能需要使用 TaskStackBuilder,以便如果用户从 PostActivity 点击返回,它会返回到 MessageActivity
        TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(MyFirebaseInstanceService.this);
        taskStackBuilder.addNextIntentWithParentStack(intent);
        pendingIntent = taskStackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
    }
    .....
}

这里是如何使用 TaskStackBuilder 的链接:

英文:

Just a simple check will do the job, you need to send some data that you check to know if the notification comes from comment or like or post or whatever

private void sendNotification(RemoteMessage remoteMessage) {
.....
String user = remoteMessage.getData().get("user");
String nType= remoteMessage.getData().get("type");// here type is some data you send
int j = Integer.parseInt(user.replaceAll("[\\D]", ""));
...
Intent intent = null;
PendingIntent pendingIntent=null;
Bundle bundle = new Bundle();
if(nType.equals("message")){
intent=new Intent(MyFirebaseInstanceService.this, MessageActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);// here you can change launch mode if you want
bundle.putString("id", "124");// here add your data to the bundle
intent.putExtras(bundle);
pendingIntent = PendingIntent.getActivity(MyFirebaseInstanceService.this, j, intent, PendingIntent.FLAG_ONE_SHOT);
}else  if(nType.equals("comment")){
intent = new Intent(MyFirebaseInstanceService.this, PostActivity.class);
bundle.putString("postId", "134");// here add your data to the bundle
intent.putExtras(bundle);
// here You may need to user TaskStackBuilder  so if the user click back from PostActivity it goes to MessageActivity
TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(MyFirebaseInstanceService.this);
taskStackBuilder.addNextIntentWithParentStack(intent);
pendingIntent = taskStackBuilder
.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
}
.....
}

here is a link to how to use TaskStackBuilder

huangapple
  • 本文由 发表于 2020年8月21日 22:07:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/63524411.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定