Android - 如何使用Action创建通知

时间:2018-01-15 10:16:26

标签: android android-notifications

我正在创建这样的通知。

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

Notification notification = builder.build();

我想通过

为我的通知添加操作
builder.addAction();

要实现addAction(icon, title, pendingIntent);已弃用

我的geal是创建没有图标的通知操作,我该如何实现?

2 个答案:

答案 0 :(得分:2)

使用NotificationCompat代替Notification,如下所示:

Notification.Action action = new NotificationCompat.Action(icon, title, pendingIntent);
Notification notification = new NotificationCompat.Builder(context)
       .addAction(action)
       .build();

答案 1 :(得分:2)

单击操作按钮时无法直接调用方法。

您需要使用PendingIntent与BroadcastReceiver或Service来执行此操作。

以下是与广播接收者等待意图的示例。

首先制作通知

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);
...
}

现在接收此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(){

}
}

不要忘记在清单中声明BroadCast Receiver

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

希望它对你有所帮助。