将变量传递给FirebaseMessagingService

时间:2018-11-26 17:30:17

标签: java android firebase service firebase-cloud-messaging

我想在FirebaseMessagingService中使用已打开活动的一些变量,这可能吗?我的意思是例如在服务中获取前台活动名称或意图的附加内容。 谢谢。

1 个答案:

答案 0 :(得分:1)

是的。看一下这个样本。

  public class ConcreteMessagingService extends FirebaseMessagingService {

@Override
public void onMessageReceived(RemoteMessage rMessage) {

    String some_data = "0";
    String another_data = "0";

    if (rMessage.getData().size() > 0) {
        some_data = rMessage.getData().get("some_data");
        another_data = rMessage.getData().get("another_data");
    }

    String click_action = rMessage.getNotification().getClickAction();

    //generate notification here
    sendNotification(rMessage.getNotification().getBody(), rMessage.getNotification().getTitle(), some_data, another_data, click_action);
}

private void sendNotification(String some_data, String another_data) {
    Intent intent = new Intent(click_action);
    intent.putExtra("some_data", some_data);
    intent.putExtra("another_data", another_data);

    PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent,
            PendingIntent.FLAG_ONE_SHOT);

    Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
    notificationBuilder.setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle(title)
            .setContentText(contentText)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);

    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(0, notificationBuilder.build());
}}

and onCreate()和onResume()

   notification_Y_N = (TextView) findViewById(R.id.notification_Y_N);
    some_data_text = (TextView) findViewById(R.id.some_data_text);

    Intent intent_o = getIntent();
    String some_data = intent_o.getStringExtra("some_data");
    String another_data = intent_o.getStringExtra("another_data");

    notification_Y_N.setText(another_data);
    some_data_text.setText(some_data);