簡體   English   中英

點擊 FCM 通知后如何在應用程序不在后台時重新打開應用程序

[英]how to reopen app just when it is not in background after tap on FCM notitiction

我正在使用 FCM 向我的應用程序發送通知,但出現問題。 如果我的用戶正在使用該應用程序並且只需按主頁按鈕(而不是后退鍵)退出應用程序並收到通知,然后按通知,我的應用程序將重新打開。 如果用戶按下后退按鈕,他/她將退出重新打開的應用程序,並且他/她將在按下主頁按鈕之前被定向到應用程序的最后一個 state。(換句話說,用戶應該按下后退按鈕兩次,一次用於退出重新打開的應用程序,另一次用於退出后台的應用程序)

如果應用程序在后台,我如何加載它的最后一個 state,如果它不在后台,如何通過點擊通知重新打開應用程序?

編輯:

我將“onMessageReceived”更改為以下代碼但沒有任何改變:


class MyFireBase() : FirebaseMessagingService(){

    override fun onNewToken(p0: String) {
        super.onNewToken(p0)
    }

    override fun onMessageReceived(p0: RemoteMessage) {
        try {

            val intent = Intent()
            intent.action = "ACTION_STRING_ACTIVITY"
            intent.putExtra("category", p0.data["category"])
            sendBroadcast(intent)


            val notificationIntent = Intent(baseContext, MainActivity::class.java)
            notificationIntent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
             PendingIntent.getActivity(
                baseContext,
                1,
                notificationIntent,
                PendingIntent.FLAG_UPDATE_CURRENT
            )

            super.onMessageReceived(p0)
        } catch (e: Exception) {
            e.printStackTrace()
        }


    }

}

如果您使用 Firebase Cloud Messaging 向您的應用程序發送通知,則意味着您可以創建自己的通知。 然后你所要做的就是為你的intent設置適當的FLAG

public class MyFirebaseMessagingService extends FirebaseMessagingService {

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    try {
        Intent notificationIntent = new Intent(context, MainActivity.class);
        //Intent.FLAG_ACTIVITY_NEW_TASK Launches a new instances of your Activity. 
        //So if there is already one in background, there will be two instances.
        //Intent.FLAG_ACTIVITY_CLEAR_TOP is what you want, it resumes the last
        //session if there is any, or launches a new instance if there is no instance in background
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, requestID, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        //do the rest
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }

}

我通過更改活動的啟動模式解決了這個問題,因此,在 AndroidManifest 中,我為 MainActivity 設置launchMode = singleTask

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM