6.0之后Notification的基本用法(部分翻译自google官方文档)

1、creat a Notification Builder

一个Builder至少包含:

  • a small icon 用setSmallIcon来设置
  • a title 用setContentTitle来设置
  • detail text 由setContentText来设置
eg:
NotificationCompat.Builder mBuilder =  new NotificationCompat.builder(this).setSmallIcon(R.drawable.notification-icon).setContentTitle("My notification").setContentText("Hello World");


2、Define the notification‘s action
一个通知至少由一个action,action通常让用户通过通知跳转到一个应用的活动中,它们可以看作是产生通知或做更多工作的一个event,在通知中,action由包含与Intent中的pendingIntent来定义,而这个Intent通常在你应用的Acitivity中开始。
如何构造一个pendingIntent取决与你的Activity是什么类型的,当你从通知中开启一个活动时,你必须保存用户的导航体验(回到之前的活动界面),在下面代码中,单击通知打开一个新的活动,拓展了通知的功能,这种情况下就不会创建一个人工的回堆栈。
eg:
Intent resultIntent = new Intent(this,resultAction.Class);
//由于点击通知代开的是一个新的活动,并不需要创建一个人工返回栈
PendingIntent resultPendingIntent = PendingIntent.getActivity(this,0,resultIntent,PendingIntent.FLAG_UPDATE_CURRENT);

3、Set the notification's click behavior
为了将之前创建的pendingIntent和手势联系起来,用Notification.Builder中的合适的方法来实现。比如当用户点击一个通知栏的时候开启一个Activity,通过setContentIntent()方法将PendingIntent加入。
eg:
mBuilder.setContentIntent(resultPendingIntent);

4、Issue the Notification
发通知
① 获得NotificationManager的实例
②用notify方法让通知显示出来
③调用build()方法返回一个设置好的Notification对象
eg:
NotificationCompat.Builder mBuilder;
//为notification设置id
int mNotificationId = 001;
//获得NotificationManager服务的实例
NotificationManager mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//建立一个通知 然后发出来
mNotification.notify(mNotificationId,mBuilder.build());


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值