自学Android之通知Notification

什么是通知(Notification)

通知是一个可以在应用程序正常的用户界面之外显示给用户的消息。
通知发出时,它首先出现在状态栏的通知区域中,用户打开通知抽屉可查看通知详情。通知区域和通知抽屉都是用户可以随时查看的系统控制区域。

通知基本用法

通知的必要属性

一个通知必须包含以下三项属性:

  • 小图标,对应 setSmallIcon()
  • 通知标题,对应 setContentTitle()
  • 详细信息,对应 setContentText()
其他属性为可选项, 尽管其他都是可选的,但一般都会为通知添加至少一个动作(Action),这个动作可以是跳转到Activity、启动一个Service或发送一个Broadcas等。 通过以下方式为通知添加动作:
  • 使用PendingIntent
  • 通过大视图通知的 Action Button //仅支持Android 4.1 (API level 16)及更高版本,稍后会介绍

创建一个普通通知的代码为

//实例化通知管理器
        NotificationManager notificationManager= (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        //实例化通知
        NotificationCompat.Builder builder=new NotificationCompat.Builder(this);

        builder.setContentTitle("今天情人节,大事件");
        builder.setContentText("不要放孔明灯,特别是在机场附近,否则2-10W");
        builder.setDefaults(NotificationCompat.DEFAULT_ALL);

        builder.setAutoCancel(true);

        builder.setSmallIcon(android.R.drawable.ic_media_play);

        builder.setContentIntent(PendingIntent.getActivity(this,0x102,new Intent(this,RingActivity.class),0));

        Notification notification=builder.build();

        //发送通知
        notificationManager.notify(0x101,notification);
创建自定义通知的代码为
  //实例化通知管理器
        NotificationManager notificationManager= (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        //实例化通知
        NotificationCompat.Builder builder=new NotificationCompat.Builder(this);

        builder.setDefaults(NotificationCompat.DEFAULT_ALL);

        builder.setAutoCancel(true);

        builder.setSmallIcon(android.R.drawable.ic_media_play);


        RemoteViews remoteView = new RemoteViews(this.getPackageName(),R.layout.remotelayout);

        Notification notification=builder.build();
        notification.contentView = remoteView; // 设置下拉图标
        notification.bigContentView = remoteView; // 防止显示不完全,需要添加apisupport
        notification.flags = Notification.FLAG_ONGOING_EVENT;

        //发送通知
        notificationManager.notify(0x101,notification);

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值