处理当前活动的安卓推送通知



我已经实现了Android推送通知,当应用程序运行时,我可以使用此方法处理扩展FirebaseMessagingService

@Override
public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
...
}

但我真正需要的是获取当前活动中的通知数据,以更新某些字段以让用户实时看到它。但是我找不到一种方法来做到这一点。有人可以帮助我吗?

创建本地广播接收器
当您在 FirebaseMessagingService 收到通知时,您会使用本地广播接收器将数据发送到所需的活动。它既简单又安全。

在您的 FirebaseMessagingService 上

@Override
public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
//Take the data from message received
String myData = remoteMessage.get("MyDataKey");
//Send data through a local broadcast receiver
Intent intent = new Intent("IntentFilterAction");
intent.putExtra("MyDataKey", myData);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

在活动上创建

//Create BroadcastReceiver
BroadcastReceiver broadcastReceiver = new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
//Get data from intent
String mydata = intent.getExtras
}
};
IntentFilter intentFilter = new IntentFilter("IntentFilterAction");
LocalBroadcastManager.getInstance(getContext()).registerReceiver(broadcastReceiver, intentFilter);

在销毁活动时

//Unregister BroadcastReceiver
LocalBroadcastManager.getInstance(getContext()).unregisterReceiver(broadcastReceiver);

希望对:)有所帮助

从文档中查看以下内容:

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
updateData(remoteMessage.getData());
}
}

public void updateData(Map<String, String> data){
// update your data here
//ex: editText1.setText("text");
}

相关内容

  • 没有找到相关文章