创建一个Notification (通知)

本文介绍如何使用NotificationCompat.Builder创建Android通知,包括设置图标、标题、文本,定义点击行为以跳转到应用内活动,并展示了如何发布通知。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这个例子是基于Notification.Builder类来实现的,最低限度的,一个Builder对象应该包括以下:

  • 一个小icon
  • 一个标题 title
  • 一个文本
NotificationCompat.Builder mBuilder =
    new NotificationCompat.Builder(this)
    .setSmallIcon(R.drawable.notification_icon)
    .setContentTitle("My notification")
    .setContentText("Hello World!");

定义一个Notification的行为(action)

虽然 行为 是可选的,但是你至少应该添加一个行为,也就是可以让 用户通过店家 Notification 直接跳转到一个你app的activity的行为。

这个行为,由 包含一个Intent的 pendingIntent 定义。

如何构造你的pendingIntent,由你想要的打开的activity的类型有关,有时候你只是打开其中的一个片段,那么你必须创建一个新的back stack,但是有时候你是打开一个全新的activity,那么就不需要创建一个backstack了,如下代码:

Intent resultIntent = new Intent(this, ResultActivity.class);
...

PendingIntent resultPendingIntent =
    PendingIntent.getActivity(
    this,
    0,
    resultIntent,
    PendingIntent.FLAG_UPDATE_CURRENT
);

添加一个点击事件

PendingIntent resultPendingIntent;
...
mBuilder.setContentIntent(resultPendingIntent);

发布一个Notification

  • 获取一个 NotificationManager 的实例
  • 使用 notify() 方法来发布,指明 发布Id
  • 用 build() 方法来创建一个 Notification 对象
NotificationCompat.Builder mBuilder;
...
// Sets an ID for the notification
int mNotificationId = 001;
// Gets an instance of the NotificationManager service
NotificationManager mNotifyMgr =
        (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Builds the notification and issues it.
mNotifyMgr.notify(mNotificationId, mBuilder.build());

创建一个Notification的最简单方式

NotificationCompat.Builder mBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("hello notification")
                .setContentText("how are you?");

        Intent resultIntent = new Intent(this,MainActivity.class);

        PendingIntent resultPendingIntent = PendingIntent.getActivity(this,0,resultIntent,PendingIntent.FLAG_UPDATE_CURRENT);

        mBuilder.setContentIntent(resultPendingIntent);

        int Id = 001;

        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        manager.notify(Id,mBuilder.build());
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值