3

I'm creating a notification like this.

Notification.Builder builder = new Notification.Builder(context);
        builder.setContentTitle(notifyMessage1)
                .setContentText(notifyMessage2)
                .setSmallIcon(R.mipmap.ic_launcher);

Notification notification = builder.build();

I want to add a action to my notification with

builder.addAction();

To realize addAction(icon, title, pendingIntent); is deprecated

My geal is to create a notification action without an icon, how can i achieve that?

braulio.cassule
  • 1,322
  • 4
  • 14
  • 23

2 Answers2

14

You can't directly call methods when you click action buttons.

You require to use PendingIntent with BroadcastReceiver or Service to perform this.

Here is an example of Pending Intent with Broadcast Reciever.

First build a Notification

public static void createNotif(Context context){

...
//This is the intent of PendingIntent
Intent intentAction = new Intent(context,ActionReceiver.class);

//This is optional if you have more than one buttons and want to differentiate between two
intentAction.putExtra("action","actionName");

pIntentlogin = PendingIntent.getBroadcast(context,1,intentAction,PendingIntent.FLAG_UPDATE_CURRENT);
drivingNotifBldr = (NotificationCompat.Builder) new NotificationCompat.Builder(context)
        .setSmallIcon(R.drawable.steeringwheel)
        .setContentTitle("NoTextZone")
        .setContentText("Driving mode it ON!")
        //Using this action button I would like to call logTest
        .addAction(R.drawable.smallmanwalking, "Turn OFF driving mode", pIntentlogin)
        .setOngoing(true);
...
}

Now the receiver which will receive this Intent

public class ActionReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {

    //Toast.makeText(context,"recieved",Toast.LENGTH_SHORT).show();

    String action=intent.getStringExtra("action");
    if(action.equals("action1")){
        performAction1();
    }
    else if(action.equals("action2")){
        performAction2();

    }
    //This is used to close the notification tray
    Intent it = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
    context.sendBroadcast(it);
}

public void performAction1(){

}

public void performAction2(){

}
}

Do not forget to declare BroadCast Receiver in Manifest

<receiver android:name=".ActionReceiver"></receiver>

Hope it helps you.

  • 1
    I was having an issue getting Local broadcasters to receive data until I added it in the manifest file – lasec0203 Oct 30 '19 at 06:25
8

Use the NotificationCompat instead of Notification like this:

Notification.Action action = new NotificationCompat.Action(icon, title, pendingIntent);
Notification notification = new NotificationCompat.Builder(context)
       .addAction(action)
       .build();
Peter Haddad
  • 78,874
  • 25
  • 140
  • 134