Android - 如何创建带有操作的通知

4
我正在创建这样的通知。
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);已被弃用

我的目标是创建一个没有图标的通知行动,我该如何实现?


这个链接可能会有所帮助。 - ADM
好的,但是我不想要一个图标。 - braulio.cassule
我认为如果你不需要图标,可以传递0。我对此不太确定。 - ADM
2个回答

16

点击操作按钮时,您无法直接调用方法。

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

这是一个使用BroadcastReceiver的PendingIntent示例。

首先构建一个通知

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

}
}

不要忘记在清单文件中声明广播接收器

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

希望这能对你有所帮助。


1
我在使用本地广播接收数据时遇到了问题,直到我将其添加到清单文件中才解决了。 - lasec0203

9
请使用NotificationCompat而不是像这样使用Notification:
Notification.Action action = new NotificationCompat.Action(icon, title, pendingIntent);
Notification notification = new NotificationCompat.Builder(context)
       .addAction(action)
       .build();

NotificationCompat也被弃用了吗? - braulio.cassule
@braulio.cassule 不,不是这样的。 - Thamsanqa Mahlaola
它现在已经过时了。https://developer.android.com/reference/android/support/v4/app/NotificationCompat - Shawn
2
android.support.v4.app.NotificationCompat已被弃用,但androidx.core.app.NotificationCompat并没有被弃用,并且在当前文档中广泛使用。 - Jeff Hutchins

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接