startActivity not working inside onMessageReceived in fcm

Viewed 1001

I know there are many thread discussing this problem. I have tried almost all of solutions on that threads, but unfortunately that didn't work in my case.

Basically, what I want to do is, I want to start an activity immediately after onMessageReceived is called without issuing notification.

This is my code:

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())
        })
    }
...

The problem is, if the app is in foreground, NewOrderActivity is opened. But if the app is in background, NewOrderActivity is not opened. I have tried using BroadcastReceiver but that also does not work. Current compileSdkVersion and targetSdkVersion is set to 29. I have changed it to 28 but also does not work

2 Answers

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.

Example code :- You need to specify click_action in your notification payload like this

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

Now in manifest file do this in your NewOrderActivity activity tag

<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>
Related