Noficication的那些事

Noficication的那些事(一)

应用中经常会使用通知与用户进行交互,对于创建通知,官方建议使用NotificationCompat.Bulder或则它的子类,这样能够很好的适配不同版本的设备。

创建 Notification Builder

创建通知,最少需要设置通知的三个属性:

  • 小图标 通过 setSmallIcon()  设置;
  • 标题 通过 setContentTitle() 设置;
  • 详细文字 通过 setContentText() 设置;

例如:

NotificationCompat.Builder mBuilder =
    new NotificationCompat.Builder(this)
    .setSmallIcon(R.drawable.notification_icon)
    .setContentTitle("My notification")
    .setContentText("Hello World!");
定义通知的行为

一般的,我们会为通知设置点击行为,定义通知的行为需要用到PendingIntent ,

下面构造了一个PendingIntent 用来打开 ResultActivity

Intent resultIntent = new Intent(this, ResultActivity.class);
...
// Because clicking the notification opens a new ("special") activity, there's
// no need to create an artificial back stack.
PendingIntent resultPendingIntent =
    PendingIntent.getActivity(
    this,
    0,
    resultIntent,
    PendingIntent.FLAG_UPDATE_CURRENT
);
设置通知的行为

定义好了通知的行为,下面我们需要为Notification关联PendingIntent,代码如下:

PendingIntent resultPendingIntent;
...
mBuilder.setContentIntent(resultPendingIntent);
发布通知
  • 调用mBuilder.builder得到指定的待发布的通知;

  • 在发布通知之前,首先需要获取NotificationManager的实例;

  • 使用notify() 发布通知,在调用notify()发布通知的时候,指定通知的id,以后可以通过这个id来更新通知的内容;

    例如:

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

获取官方原文

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值