Android Notification通知栏的创建

因为刚上线,下一版的需求还没出,时间也是比较充裕的,所以看了一下Notification

如果我们想自己创建一个默认通知栏条目,包括点击触发的一些事件其实也是一件非常简单的事情

1.系统已经提供了相应的manager

NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

2.注册广播以便接收用户点击通知栏触发的事件

Intent intentClick = new Intent(this, NotificationClickReceiver.class);
intentClick.setAction("notification_clicked");
intentClick.putExtra("type", 1);
PendingIntent pendingIntentClick = PendingIntent.getBroadcast(this, 0, intentClick, PendingIntent.FLAG_UPDATE_CURRENT);

3.写一个默认的通知栏

 Notification.Builder notification = new Notification.Builder(this);
 //设置震动
 //notification.setDefaults(Notification.DEFAULT_VIBRATE);
 //设置提示音
 //notification.setDefaults(Notification.DEFAULT_SOUND);
 //设置震动和提示音
 notification.setDefaults(Notification.DEFAULT_ALL);
 notification.setContentTitle("我是标题");
 notification.setSmallIcon(R.mipmap.ic_launcher);
 notification.setContentText("我是内容");
 //设置点击通知栏触发的事件
 notification.setContentIntent(pendingIntentClick);
 //设置清除通知栏触发的事件
 notification.setDeleteIntent(null);

4.好啦,notify一个通知栏

manager.notify(1, notification.build());

注意:manager.notify第一个是id,是用来生成和取消通知栏条目的,必须与intentClick.putExtra(“type”, 1);中的1保持一致,这样在广播接收中才能判断接收到的是哪个通知栏的消息

5.注册一个广播接收点击消息

public class NotificationClickReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getIntExtra("type", 0) == 1) {
            Log.i("ytt", "收到了一条消息");
            Toast.makeText(context, intent.getAction(), Toast.LENGTH_SHORT).show();
            NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            //取消通知栏显示
            manager.cancel(intent.getIntExtra("type", 0));
        }
    }
}

6.还需要再AndroidManiFest.xml里注册广播

<receiver android:name="xxx.NotificationClickReceiver"/>

如果只允许该receiver接收指定的action的话就要添加过滤器了

<receiver android:name="xxx.NotificationClickReceiver">
    <intent-filter>
        <action android:name="你的action"/>
        <action android:name="你的action"/>
        .......
    </intent-filter>
</receiver>

就这样啦

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值