Home > OS >  Any suggestions on how to call a method in main activity after pressing a notification button?
Any suggestions on how to call a method in main activity after pressing a notification button?

Time:08-05

I am trying to update a recycler view, which I can update with a method in main activity, but I am trying to get to it from a notification button, which opens a broadcast receiver and manipulates data, but I need to call the method in main activity to update my recycler view. I am trying to do this from the recycler view. I only need to do it if the recycler view in main activity is on screen, I can do it from on resume just fine, just want to to update if main activity is on with recycler view active.

CodePudding user response:

You can use another broadcast to communicate with Main Activity and update notification when main activity is active

    // broadcast
    val br: BroadcastReceiver = object:BroadcastReceiver(){
        override fun onReceive(context: Context?, intent: Intent?) {
            if (intent?.action == UPDATE_DATA){
                // update recycler view
            }
        }
    }

    var UPDATE_DATA = "com.example.broadcast.UPDATE_DATA"

    override fun onResume() {
        super.onResume()
        val filter = IntentFilter(UPDATE_DATA).apply {
        }
        LocalBroadcastManager.getInstance(this).registerReceiver(br, filter)
    }

    override fun onPause() {
        LocalBroadcastManager.getInstance(this).unregisterReceiver(br)
        super.onPause()
    }

    // send broadcast from notification broadcast
    Intent().also { intent ->
        intent.action = "com.example.broadcast.MY_NOTIFICATION"
        intent.putExtra("data", "Nothing to see here, move along.")
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent)
    }
  • Related