Android - 如何创建带 Action 的通知

标签 android android-notifications

<分区>

我正在创建这样的通知。

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

Notification notification = builder.build();

我想在我的通知中添加一个 Action

builder.addAction();

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

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

最佳答案

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

您需要将 PendingIntent 与 BroadcastReceiver 或服务一起使用才能执行此操作。

这是一个带有广播接收器的待定 Intent 示例。

首先构建一个通知

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

}
}

不要忘记在 Manifest 中声明 BroadCast Receiver

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

希望对你有帮助。

关于Android - 如何创建带 Action 的通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48260875/

相关文章:

android - 无法启动服务 - 需要 ACCESS_MOCK_LOCATION 安全设置

java - 如何对 Android 相机图像进行傅立叶变换?

android - 当应用程序从后台终止时从状态栏中删除通知

android - 我应该使用什么权限来接收 android 通知?

android - 如何在 setongoing(true) 之后删除持久通知?

android - 您可以从 Html 5 Web 应用程序启动 native 相机应用程序吗?

java - Android 中的向后兼容性和 SDK 更新

java - 如何在 ListView 适配器线性布局中添加项目

android - 如何仅在选中 CheckBoxPreference 时推送 firebase 通知?

audio - Xamarin本地通知自定义声音无法播放