当前位置: 首页 > 知识库问答 >
问题:

单击通知以打开“我的活动”时的firebase消息

戚兴邦
2023-03-14

firebase工作得很好,在状态栏上推送通知,但我的挑战是当通知被点击时,我希望它带我到我的自定义活动而不是默认的启动器,我该怎么做呢?

public class CustomActivity extends AppCompatActivity {

private static final String TAG = "CustomActivity";


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    TextView mymessage = (TextView) findViewById(R.id.mymessage);

    // If a notification message is tapped, any data accompanying the notification
    // message is available in the intent extras. In this sample the launcher
    // intent is fired when the notification is tapped, so any accompanying data would
    // be handled here. If you want a different intent fired, set the click_action
    // field of the notification message to the desired intent. The launcher intent
    // is used when no click_action is specified.
    //
    // Handle possible data accompanying notification message.
    // [START handle_data_extras]
    if (getIntent().getExtras() != null) {
        for (String key : getIntent().getExtras().keySet()) {
            String value = String.valueOf(getIntent().getExtras().get(key));
            Log.d(TAG, "Key: " + key + " Value: " + value);
            //
            Toast.makeText(getApplicationContext() , value , Toast.LENGTH_SHORT).show();


        }

        //Toast.makeText(getApplicationContext() , String.valueOf(getIntent().getExtras().get("message")) , Toast.LENGTH_SHORT).show();


    }
    // [END handle_data_extras]

    Button subscribeButton = (Button) findViewById(R.id.subscribeButton);
    subscribeButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // [START subscribe_topics]
            FirebaseMessaging.getInstance().subscribeToTopic("news");
            // [END subscribe_topics]

            // Log and toast
            String msg = getString(R.string.msg_subscribed);
            Log.d(TAG, msg);
            Toast.makeText(CustomActivity.this, msg, Toast.LENGTH_SHORT).show();
        }
    });

    Button logTokenButton = (Button) findViewById(R.id.logTokenButton);
    logTokenButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Get token
            String token = FirebaseInstanceId.getInstance().getToken();

            // Log and toast
            String msg = getString(R.string.msg_token_fmt, token);
            Log.d(TAG, msg);
            Toast.makeText(CustomActivity.this, msg, Toast.LENGTH_SHORT).show();
        }
    });
}

这是我想在通知计时时打开的自定义活动。通知来自Firebase cloud Messaging。

public class MyFirebaseMessagingService extends FirebaseMessagingService {

private static final String TAG = "MyFirebaseMsgService";

/**
 * Called when message is received.
 *
 * @param remoteMessage Object representing the message received from Firebase Cloud Messaging.
 */
// [START receive_message]
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    // [START_EXCLUDE]
    // There are two types of messages data messages and notification messages. Data messages are handled
    // here in onMessageReceived whether the app is in the foreground or background. Data messages are the type
    // traditionally used with GCM. Notification messages are only received here in onMessageReceived when the app
    // is in the foreground. When the app is in the background an automatically generated notification is displayed.
    // When the user taps on the notification they are returned to the app. Messages containing both notification
    // and data payloads are treated as notification messages. The Firebase console always sends notification

    // [END_EXCLUDE]

    // TODO(developer): Handle FCM messages here.
    Log.d(TAG, "From: " + remoteMessage.getFrom());

    // Check if message contains a data payload.
    if (remoteMessage.getData().size() > 0) {
        Log.d(TAG, "Message data payload: " + remoteMessage.getData());
        System.out.print("Message data payload :" + remoteMessage.getData());

    }

    // Check if message contains a notification payload.
    if (remoteMessage.getNotification() != null) {
        Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
        System.out.print("Message Notification Body :" + remoteMessage.getNotification().getBody());
    }



    // Also if you intend on generating your own notifications as a result of a received FCM
    // message, here is where that should be initiated. See sendNotification method below.


}
// [END receive_message]



/**
 * Create and show a simple notification containing the received FCM message.
 *
 * @param messageBody FCM message body received.
 */
private void sendNotification(String messageBody) {
    Intent intent = new Intent(this, CustomActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);

    Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_stat_ic_notification)
            .setContentTitle("FCM Message")
            .setContentText(messageBody)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);

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

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

}

这是侦听来自FireBase的通知的服务。

共有1个答案

景令秋
2023-03-14
private void showNotification(String msg) {
    //Creating a notification
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    builder.setSmallIcon(R.drawable.ic_launcher);
    Intent intent = new Intent().setClassName("packagename", "packagename.YourActivityname"); // give any activity name which you want to open
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
    builder.setContentIntent(pendingIntent);
    builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher));
    builder.setContentTitle("FireBase");
    builder.setContentText(msg);
    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    notificationManager.notify(1, builder.build());
}

希望对你有帮助!

 类似资料:
  • 我有一个带有通知的应用程序,如果我单击它们,就会打开某个活动。我想要的是,如果我点击通知,活动已经打开,它不是重新开始,但只是出现在前面。 我可以用标志来管理它吗?还是我应该在SharedPreferences中存储一个变量来检查它是否已打开? 谢谢!

  • 我已经尝试了所有的方法,但它不适合我。我想打开或恢复应用程序,无论屏幕打开,同时单击通知。 我使用了以下方法:

  • 我有两个活动Main activity和ReceivedMessageActivity。以及一个后台服务,用于从中获取上下文并传递给SMSReceiver,SMSReceiver扩展BroadcastReceiver以接收sms。当收到短信时,SMSReceiver会创建通知。我希望当我点击通知时,如果应用程序未运行ReceivedMessageActivity,则打开该通知;如果应用程序正在运行

  • 我正在工作的应用程序中,我被要求显示通知。对于通知,我使用的是FireBase云消息(FCM)。我能够得到通知,当应用程序在后台。 2.)MyFirebaseInstanceIDService 这是我在MyFirebaseMessagingService类中为onMessageReceived()方法编写的代码示例。

  • 我目前遇到以下问题: 我已经实现了自定义FirebaseMessagingService,并且覆盖了方法onMessageReceived()。此外,当应用程序在后台时,我从getExtras()获取捆绑包 我需要通知内容,以便在db中本地保存 发生了什么: 当应用程序处于后台时,从Firebase控制台发送3个通知 创建了3个状态栏通知 单击其中一个- 你能帮忙吗? 启动器活动代码: 自定义Fi