📜 ⬆️ ⬇️

How to assign a custom method for a button in a notification

When creating buttons in a notification, you cannot simply assign listeners to them, as we used to do by editing the user interface. The main way to assign actions in a notification is intents (Intent) - intentions.

And if in order to assign a transition action to a button, it is sufficient to simply create a corresponding intent, within which the necessary action will be described, namely, from where and where we are going, then in our case it will be necessary to do the following: assign the intention to the button, pass it an Action to work with the intent filter, create a BroadcastReciver that will catch our Intent and then already execute the method we need.

So, first create our notification. In my example, I carried out all the following actions in a separate method sendNotification. But first we need to create a string in which we write the key so that our receiver can catch exactly our Intent. Since many applications are constantly throwing intents into the system, this key must be unique

//   String BROADCAST_ACTION = "com.example.uniqueTag"; public void sendNotification () { NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this); Intent intent = new Intent(BROADCAST_ACTION); //          Intent   .getBroadcast PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intentStopTrip, 0); //  Notification BuilderNote = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.ic_example) .setContentTitle("Example title") .setContentText("Example text") .setContentIntent(pendingIntentPush) //        pendingIntent .addAction(R.mipmap.ic_example, "Button name", pendingIntent) .build(); //   BuilderNote.flags |= Notification.FLAG_AUTO_CANCEL; notificationManager.notify(0, BuilderNote); } 

Now you need to create a receiver BroadCastReciver. To do this, click RMB on your folder app-> New-> Other-> BroadcastReciver. Next, give it a name, and in the file that opens we need to remove the stub as a stuffing exception, writing in its place our method
')
 public class ExampleReciver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { exampleMethod(); } } 

But beyond that, we need to configure the Intent Filter for our receiver to let it know exactly which Inetnt it needs to receive. To do this, go to the manifest and the code block of our receiver, register the Intent Filter, where we write the contents of the string variable BROADCAST_ACTION created at the very beginning

 <receiver android:name=".StopTimerReciver" android:enabled="true" android:exported="true"> <intent-filter> <action android:name="com.example.uniqueTag" /> </intent-filter> </receiver> 

That's all, now in the case of clicking on the button we created in the notification, the method defined in the body BroadcastReciver will be launched

Source: https://habr.com/ru/post/354758/


All Articles