Search code examples
androidbroadcastreceiverandroid-notificationsandroid-pendingintent

Implement setOnClickPendingIntent from notification


I build custom notification that contain button and i want to listin when user press on it.

The button should not open any activity but only logic staff like change song.

the Code:

        RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.notification);
        contentView.setTextViewText(R.id.toptext, nowPlayingTitle);

        //this not work
        Intent intent = new Intent(this, receiver.class);
        intent.putExtra("UNIQ", "1");
        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                this.getApplicationContext(), 234324243, intent, PendingIntent.FLAG_CANCEL_CURRENT)
        contentView.setOnClickPendingIntent(R.id.imageButtonPlay,
                pendingIntent);
        notification.contentView = contentView; 

        // this is to return to my activity if click somwhere else in notification
        Intent notificationIntent = new Intent(this, MYACTIVITY.class);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
        notification.contentIntent = contentIntent;

        mNotificationManager.notify(NOTIFICATION_ID, notification);

I don't get the hang of the setOnClickPendingIntent what need to be in the second param? How can i just call a function after user press on the button?

im probably missing something cause i dont understand the receiver side and what happend after user press


Solution

  • You are missing the fact that the button you created actually doesn't belong to your application. It is created in another context, in another process. There is no way it can call your function.

    Instead, when the user taps the button, that pending intent is fired. You can catch it by your receiver (in your activity), check some parameters and do the action. Or you can implement a service and handle this intent in background. I'd prefer this way.