Android - How to create a Notification with Action [duplicate]

你说的曾经没有我的故事 提交于 2020-08-24 05:00:20

问题


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?


回答1:


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();



回答2:


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.



来源:https://stackoverflow.com/questions/48260875/android-how-to-create-a-notification-with-action

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!