Android Notification通知栏的创建

来源:互联网 发布:js实现文件上传和下载 编辑:程序博客网 时间:2024/06/04 19:30

因为刚上线,下一版的需求还没出,时间也是比较充裕的,所以看了一下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
原创粉丝点击