startActivity 在 fcm 中的 onMessageReceived 中不起作用

startActivity not working inside onMessageReceived in fcm

我知道有很多帖子在讨论这个问题。我已经尝试了关于该线程的几乎所有解决方案,但不幸的是,这对我来说不起作用。

基本上,我想做的是,我想在调用 onMessageReceived 后立即启动一个 activity,而不发出通知。

这是我的代码:

override fun onMessageReceived(p0: RemoteMessage) {
    super.onMessageReceived(p0)
    "new notif".ea()
    val data = p0.data
    val title = data["title"]
    val body = data["body"]
    val type = data["type"]

    if (type == NEW_ORDER) {
        val order = data["data"]!!.fromJsonObject(OrderModel::class.java)
        NewOrderActivity.open(this, order)
    }
...
class NewOrderActivity : BaseActivity() {

    companion object {
        fun open(c: Context, order: OrderModel) = c.startActivity(Intent(c, NewOrderActivity::class.java).apply {
            addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            putExtra("order", order.toJsonObject())
        })
    }
...

问题是,如果应用程序在前台,NewOrderActivity 会打开。但如果应用程序在后台,则 NewOrderActivity 不会打开。我试过使用 BroadcastReceiver 但这也不起作用。当前 compileSdkVersiontargetSdkVersion 设置为 29。我已将其更改为 28 但也不起作用

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 messages.

示例代码 :- 您需要在您的通知负载中指定 click_action 像这样

$noti = array
    (
    'icon' => 'new',
    'title' => 'title',
    'body' => 'new msg',
    'click_action' => 'open_NewOrderActivity'
);

现在在 manifest 文件中,在 NewOrderActivity activity 标签中执行此操作

<activity
           android:name=".NewOrderActivity">
            <intent-filter>
                <action android:name="open_NewOrderActivity" /> // should be same as in click action
               <category android:name="android.intent.category.DEFAULT"/>
           </intent-filter>
    </activity>

这是因为SYSTEM_ALERT_WINDOW权限未被用户授予。如果有人需要知道如何授予 SYSTEM_ALERT_WINDOW 权限,这里是 link