FCM点击应用处于后台状态时如何打开用户指定的活动而不是默认活动

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了FCM点击应用处于后台状态时如何打开用户指定的活动而不是默认活动相关的知识,希望对你有一定的参考价值。

当应用程序处于前台状态时,FCM工作正常并且设备上发出通知,当通知时,它会重定向到我指定的Activity,因此它正常工作。

但我的挑战是当应用程序处于后台状态时通知到来时,当点击时,它会重定向到默认活动,但我想导航到指定的活动。

这是MyFirebaseMessagingService类:

public class MyFirebaseMessagingService extends FirebaseMessagingService {
    private static final String TAG = "MyFirebaseMsgService";
    private String title, messageBody;

    /**
     * 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]

        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());
            if (remoteMessage.getData() != null && remoteMessage.getData().size() > 0) {
                title = remoteMessage.getData().get("title");
                if (TextUtils.isEmpty(title)) title = "Bocawest";
                messageBody = remoteMessage.getData().get("message");
            }
            handleNow();
        }

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

            sendNotification(remoteMessage.getNotification().getTitle(), 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.
        if (!TextUtils.isEmpty(messageBody))
            sendNotification(title, messageBody);
        //sendNotification(remoteMessage.getNotification().getBody());
        Intent intent = new Intent();
        intent.setAction("com.android.bocawest");
        sendBroadcast(intent);
    }
    // [END receive_message]

    /**
     * Handle time allotted to BroadcastReceivers.
     */
    private void handleNow() {
        Log.d(TAG, "Short lived task is done.");
    }

    /**
     * Create and show a simple notification containing the received FCM message.
     *
     * @param messageBody FCM message body received.
     */
    private void sendNotification(String title, String messageBody) {
        PendingIntent pendingIntent;
        if (SharedPreference.getBoolean(getApplicationContext(), getApplicationContext().getResources().getString(R.string.sp_isLoginIN))) {
            Intent intent = new Intent(this, NotificationsActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
        } else {
            Intent intent = new Intent(this, LoginActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
        }


        String channelId = getString(R.string.default_notification_channel_id);
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(this, channelId)
                        .setSmallIcon(R.drawable.ic_launcher)
                        .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,
                    "Bocawest",
                    NotificationManager.IMPORTANCE_DEFAULT);
            notificationManager.createNotificationChannel(channel);
        }

        notificationManager.notify(0, notificationBuilder.build());
    }
}

注意:NotificationsActivity是我指定的活动。 HomeActivity是默认活动

我知道有很多类似的问题,但我没有找到任何特定于我的用例。请帮我。

答案

@Laxman parlapelly根据Firebase standered,当您的应用在后台接收通知并且用户点击通知时,它将仅打开默认活动。如果要打开指定的活动,则必须仅通过默认活动。

例如,在用户点击通知的情况下,它将打开您的Home活动,并从HomeActivity的oncreate方法开启NotificationsActivity(以及需要捆绑包)


什么时候

当应用程序处于后台时会触发通知,然后将调用HomeActivity的onCreate()方法,以便您可以编写代码来打开通知活动

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        animLay = findViewById(R.id.root_lay_la);
        Intent intent = new Intent(this,NotificationActivity.class);
        //intent.putExtra("KEY",getIntent().getStringExtra("data")); if u need to pass data
        startActivity(intent);
    }
另一答案

if(SharedPreference.getBoolean(getApplicationContext(),getApplicationContext()。getResources()。getString(R.string.sp_isLoginIN)))在HomeActivity中写入此逻辑(在setContentView()之前的onCreate()中)所以每次用户都将重新编写 - 指向HomeActivity,如果上述条件满足,用户将再次重定向到NotificationsActivity,其他将继续使用HomeActivity

检查 - Navigate to different activities on notification click

另一答案

这对我有用 - 只需在onMessageReceived()中添加以下代码即可

Intent intent = new Intent(this, NotificationsActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |Intent.FLAG_ACTIVITY_CLEAR_TASK);

PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "111")
.setSmallIcon(R.drawable.logo)
.setContentTitle(getString(R.string.yhnn))
.setContentText(title)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
// Set the intent that will fire when the user taps the notification
.setContentIntent(pendingIntent)
.setSound(sound)
.setAutoCancel(true);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);

// notificationId is a unique int for each notification that you must define
notificationManager.notify(5, builder.build());

以上是关于FCM点击应用处于后台状态时如何打开用户指定的活动而不是默认活动的主要内容,如果未能解决你的问题,请参考以下文章

当应用程序处于后台状态时,FCM多次推送通知无法正常工作

当应用程序处于后台状态时,FCM 多个推送通知无法正常工作

如何在接收 fcm 推送通知时处于退出状态时打开应用程序 - REACT NATIVE

当应用程序从后台处于活动状态时,如何避免在本机反应中安装组件?

如何在应用程序后台接收FCM推送通知数据,但在前台点击

当应用程序处于后台状态时,Google FCM getIntent 未返回预期数据