简体   繁体   中英

cancel intent service from broadcast broadcastreceiver

I'm sending a local notification with a cancel button and when I click it, I want to cancel my intent service but the event is not getting called.

I can cancel the intent service using an activity, but when is from a notification, it is not working.

My BroadcastReceiver (the Log is showing).

class EventsReceiver: BroadcastReceiver(){
    var onEvent = {}
    override fun onReceive(context: Context?, intent: Intent?) {
        Log.i("EventsReceiver", "onReceive")
        when(intent?.action){
            Constants.ACTION_EVENT_CANCEL -> {
                Log.i("EventsReceiver", "cancel")
                onEvent()
            }
        }
    }
}

The onReceive is getting called when I click the notification button but when I call the onEvent(), the cancelTrip() function is not getting called.

My Intent Service:

override fun onCreate() {
        super.onCreate()
        notificationHelper = NotificationHelper(this)
        receiver = EventsReceiver ()
        receiver.onEvent = {
            cancelTrip()
        }
        LocalBroadcastManager.getInstance(this).registerReceiver(receiver, IntentFilter(Constants.ACTION_EVENT_CANCEL))
    }

The activity function that cancels the intent service:

private fun cancel(){
        val intent = Intent()
        intent.setAction(Constants.ACTION_EVENT_CANCEL)
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent)
    }

How I create my local notification:

val notif = NotificationCompat.Builder(ctx,NOTIFICATION_CHANNEL_ID)
        notif.setContentTitle("My App")
        notif.setContentText("Canceled trip")
        notif.setSmallIcon(R.drawable.ic_launcher_foreground)
        val notifIntent = Intent(ctx, MenuActivity::class.java)
        val pendingIntent = PendingIntent.getActivity(ctx,0,notifIntent,0)
        notif.setContentIntent(pendingIntent)
        val cancelIntent = Intent(ctx, EventsReceiver::class.java)
        val cancelPendingIntent = PendingIntent.getBroadcast(ctx,0,cancelIntent,PendingIntent.FLAG_CANCEL_CURRENT)
        notif.addAction(R.mipmap.ic_launcher, ctx.getString(R.string.cancel_trip), cancelPendingIntent)
        service.notify(NOTIFICATION_CANCEL_ID, notif.build()) 
val cancelIntent = Intent(ctx, EventsReceiver::class.java)

It's because you didn't specify the action (while creating the notification) so in here when(intent?.action) you have different action then Constants.ACTION_EVENT_CANCEL .

try using this:

val cancelIntent = Intent(Constants.ACTION_EVENT_CANCEL)

or

val cancelIntent = Intent(ctx, EventsReceiver::class.java)
cancelIntent.action = Constants.ACTION_EVENT_CANCEL

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM