Can't get extras from notification intent

Can't get extras from notification intent. Read all articles here but also does not work. Need Help. Here is my code this is my FirebaseMessagingService. Here i add different flags, but result was the same

class MyFirebaseMessagingService : FirebaseMessagingService() {

    companion object {
        const val channel_name = "Акции"
        const val DESTINATION_PUSH_KEY = "destination"
        const val VALUE_FROM_NOTIF: Int = 1
    }


    override fun onNewToken(token: String) {
        super.onNewToken(token)
        getSharedPreferences("firebaseToken", MODE_PRIVATE).edit().putString("fbToken", token)
            .putBoolean("fbTokenIsNew", true).apply();
    }

    override fun onMessageReceived(remoteMessage: RemoteMessage) {
        super.onMessageReceived(remoteMessage)
        generateNotification(
            remoteMessage.notification?.title ?:"",
            remoteMessage.notification?.body ?:""
        )
    }

    private fun generateNotification(title: String, message: String) {
        val notifIntent = Intent(this, MainActivity::class.java)
        val channelId = Resources.getSystem().getString(R.string.default_notification_channel_id)
        notifIntent.putExtra(DESTINATION_PUSH_KEY, 2)
        notifIntent.putExtra("some_key", "2")
//        notifIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP)

        val pendingIntent: PendingIntent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            PendingIntent.getActivity(
                this,
                0,
                notifIntent,
                PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
            )
        } else {
            PendingIntent.getActivity(
                this, 0, notifIntent,
                PendingIntent.FLAG_UPDATE_CURRENT
            )
        }

        val builder = NotificationCompat.Builder(applicationContext, channelId)
            .setContentTitle(title)
            .setContentText(message)
            .setSmallIcon(R.drawable.ic_notification_arus)
            .setAutoCancel(true)
            .setVibrate(longArrayOf(1000, 1000, 1000, 1000))
            .setOnlyAlertOnce(true)
            .setContentIntent(pendingIntent)

        val notificationManager =
            getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
            val channelId = resources.getString(R.string.default_notification_channel_id)
            val notificationChannel = NotificationChannel(
                channelId,
                channel_name,
                NotificationManager.IMPORTANCE_HIGH
            )
            notificationChannel.description = "Уведомления об акциях"
            notificationManager.createNotificationChannel(
                notificationChannel
            )
        }
        if (notificationManager.areNotificationsEnabled()) {
            notificationManager.notify(1, builder.build())
        }
    }
}

This is my Manifest. Also delete launchMode, and make singleTask

<activity
            android:name=".MainActivity"
            android:exported="true"
            android:label="@string/app_name"
            android:launchMode="singleTop"
            android:screenOrientation="portrait"
            android:windowSoftInputMode="adjustResize">
<!--            <nav-graph android:value="@navigation/mobile_navigation" />-->
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service
            android:name=".push.MyFirebaseMessagingService"
            android:exported="false">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>

And this is my MainActivity

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding
    private var transition: Transition? = null


    override fun onCreate(savedInstanceState: Bundle?) {
        MapKitFactory.initialize(this)
        super.onCreate(savedInstanceState)
        Utils.init(this)

//        EventBus.builder().throwSubscriberException(BuildConfig.DEBUG).installDefaultEventBus()
//        EventBus.getDefault().register(this)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        val navView: BottomNavigationView = binding.navView

        val navController = findNavController(R.id.nav_host_fragment_activity_main)

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O_MR1) {
            window.navigationBarColor = Color.BLACK
        }
        val builder = VmPolicy.Builder()
        StrictMode.setVmPolicy(builder.build())
        val appBarConfiguration = AppBarConfiguration(
            setOf(
                R.id.navigation_home, R.id.navigation_address, R.id.navigation_cabinet
            )
        )

//        setupActionBarWithNavController(navController, appBarConfiguration)
        navView.setupWithNavController(navController)
        transition = Slide(Gravity.BOTTOM)
        navController.addOnDestinationChangedListener { _, destination, _ ->
            if (destination.id != R.id.navigation_home && destination.id != R.id.navigation_address
                && destination.id != R.id.navigation_promotions
                && destination.id != R.id.navigation_cabinet
            ) {
                TransitionManager.beginDelayedTransition(navView, transition)
                navView.visibility = View.GONE
            } else {
                TransitionManager.beginDelayedTransition(navView, transition)
                navView.visibility = View.VISIBLE
            }
        }
        this.setFinishOnTouchOutside(false)
    }

    override fun onStart() {
        super.onStart()
        MapKitFactory.getInstance().onStart()
        //called when application was closed
        intent?.let { processIntent(it) }
    }

    override fun onStop() {
        super.onStop()
        MapKitFactory.getInstance().onStop()
    }

    override fun onRestart() {
        super.onRestart()
        MapKitFactory.getInstance().onStop()
    }

    fun setBottomNavigationVisibility(visibility: Int) {
        transition = Slide(Gravity.BOTTOM)
        TransitionManager.beginDelayedTransition(binding.navView, transition)
        binding.navView.visibility = visibility
    }

    fun hideKeyboardFrom(context: Context, view: View) {
        val imm = context.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(view.windowToken, 0)
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        // called when application was opened
//        Log.i("intentExtras", "onNewIntent")
        intent?.let { processIntent(it) }
    }

    private fun processIntent(intent: Intent) {
        Log.i("intentExtras", "" + intent.extras?.getString("some_key"))
        Log.i("intentExtras", "" + intent.extras?.containsKey("some_key"))
        if (intent.flags != FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) {
            if (Utils.sPref.getString(Utils.PREF_SESSION_KEY, "") != "") {
                intent.extras?.getInt(MyFirebaseMessagingService.DESTINATION_PUSH_KEY)?.let {
                    Log.i(
                        "intentExtras",
                        "" + intent.extras?.getInt(MyFirebaseMessagingService.DESTINATION_PUSH_KEY)
                    )
                    val navController = findNavController(R.id.nav_host_fragment_activity_main)
                    navController.navigate(R.id.navigation_notifications)
                    intent.removeExtra(MyFirebaseMessagingService.DESTINATION_PUSH_KEY)
                }
            }
        }
    }
}

I don't know why i get null in activity. Help!)

Try all that i find there

Upvotes: 1

Views: 743

Answers (1)

The problem was in notification. Remove the notification payload from your FCM messages in order to have the data payload delivered to the onMessageReceived method.

A find an answer there

Upvotes: 0

Related Questions