Android 之 Notification

Notification在手机的运用中是很常见的,当我们收到一个短信时,就会在我们的通知栏显示一个消息的图标和简单信息用来提示我们,这种提示就是采用的Notification来实现的。它还有其它的形式,比如下载的进度条式提示,悬挂,折叠等。
Notification 常见作用
1.显示接收到短消息、即使消息等信息 (如QQ、微信、新浪、短信)
2.显示客户端的推送消息(如有新版本发布,广告,推荐新闻等)
3.显示正在进行的事物(例如:后台运行的程序)(如音乐播放器、版本更新时候的下载进度等)

首先要介绍一个PendingIntent
PendingIntent,跟Intent相似,Intent 是即时启动,intent 随所在的activity 消失而消失,而PendingIntent它不是马上被调用,它主要用于即将发生的事情,我们可以在Notification中给定指定的事件,当用户触发事执行某一些事件。

一、普通通知#####

首先创建生成器对象,用的PendingIntent控制跳转,这里跳转到网页

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);

进行简单的属性配置

//小图标设置
mBuilder.setSmallIcon(R.mipmap.ic_launcher); 
//设置大图标
mBuilder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.lanucher));
//内容标题
mBuilder.setContentTitle("这是一个标题:"+mNotificationId);  
//内容文本   
mBuilder.setContentText("这是内容:"+mNotificationId);       
//设置数字 右下角
mBuilder.setNumber(mNotificationId);          
//设置点击 自动消失              
mBuilder.setAutoCancel(false);                               

创建PendingIntent 并设置(setContentIntent)

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.baidu.com"));
PendingIntent pendingIntent = PendingIntent.getActivity(this,
                REQUEST_CODE,
                intent,
                PendingIntent.FLAG_UPDATE_CURRENT);
//设置PendingIntent
mBuilder.setContentIntent(pendingIntent);

获取NotificationManager通过NotificationManager进行通知发布

NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
 // 利用通知管理器去发布通知
notificationManager.notify(mNotificationId,mBuilder.build());

此处mNotificationId为int类型的,如果两次通知使用同一个mNotificationId 那么将会刷新上一个通知,如果不一样,那么会另外开起一个通知。

二、大文本模式#####
  NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
        //属性配置
        mBuilder.setSmallIcon(R.mipmap.ic_launcher);
//        mBuilder.setNumber(mNotificationId);  //设置数字 右下角  如果设置 会多处一行
        mBuilder.setAutoCancel(false);         //设置点击 自动消失
        mBuilder.setDefaults(Notification.DEFAULT_ALL);
        //自定义 意图
        Intent intentCamera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        PendingIntent pendingIntentCamera = PendingIntent.getActivity(this,
                REQUEST_CODE,
                intentCamera,
                PendingIntent.FLAG_UPDATE_CURRENT
                );
        mBuilder.addAction(R.drawable.ic_camera,"拍照1",pendingIntentCamera);
        mBuilder.addAction(R.drawable.ic_camera,"拍照2",pendingIntentCamera);
        mBuilder.addAction(R.drawable.ic_camera,"拍照3",pendingIntentCamera);
        //大视图设置
        NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle();
        bigTextStyle.bigText("大文本:在使用NotificationManager.notify()发送通知的时候,需要传递一个标识符,用于唯一标识这个通知。对于有些场景,并不是无限的添加新的通知,有时候需要更新原有通知的信息,这个时候可以重写构建Notification,而使用与之前通知相同标识符来发送通知,这个时候旧的通知就被被新的通知所取代,起到更新通知的效果。"+mNotificationId);
        bigTextStyle.setBigContentTitle("大标题:"+mNotificationId);
        mBuilder.setStyle(bigTextStyle);

        //创建PendingIntent
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.baidu.com"));
        PendingIntent pendingIntent = PendingIntent.getActivity(this,
                REQUEST_CODE,
                intent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        //设置内容响应意图
        mBuilder.setContentIntent(pendingIntent);
        //设置删除时的意图
        mBuilder.setDeleteIntent(pendingIntent);

        // 利用通知管理器去发布通知
        notificationManager.notify(mNotificationId,mBuilder.build());
大文本模式

三、大图模式

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
        //属性配置
        mBuilder.setSmallIcon(R.mipmap.ic_launcher);
        mBuilder.setNumber(mNotificationId);  //设置数字 右上角
        mBuilder.setAutoCancel(false);         //设置点击 自动消失
        mBuilder.setDefaults(Notification.DEFAULT_ALL); //设置通知到达 声音 震动 灯光 等
        mBuilder.setContentText("这是内容:"+mNotificationId);

        //大图片设置
        NotificationCompat.BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();
        bigPictureStyle.setBigContentTitle("大图片");
        bigPictureStyle.setSummaryText("SummarSummarySummarySummarySummarySummarySummarySummarySummarySummarySummarySummarySummarySummaryy");
        bigPictureStyle.bigLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.ic_cancel));
        bigPictureStyle.bigPicture(BitmapFactory.decodeResource(getResources(),R.drawable.image));
        mBuilder.setStyle(bigPictureStyle);

        //创建PendingIntent
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.baidu.com"));
        PendingIntent pendingIntent = PendingIntent.getActivity(this,
                REQUEST_CODE,
                intent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        //设置内容响应意图
        mBuilder.setContentIntent(pendingIntent);
        //设置删除时的意图
        mBuilder.setDeleteIntent(pendingIntent);
        // 利用通知管理器去发布通知
        notificationManager.notify(mNotificationId,mBuilder.build());
大图模式
四、进度条模式#####
 final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
        //属性配置
        mBuilder.setSmallIcon(R.mipmap.ic_launcher);
        mBuilder.setContentTitle("正在下载:"+mNotificationId);
        mBuilder.setNumber(mNotificationId);  //设置数字 右下角
        mBuilder.setAutoCancel(false);         //设置点击 自动消失
        final NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        new Thread(
                new Runnable() {
                    @Override
                    public void run() {

                        //定义临时变量记录 保证每个线程 单独存在 作为BUG介绍
                        int tempID = mNotificationId;

                        int incr;
                        // 循环 刷新 通知
                        for (incr = 0; incr <= 100; incr+=5) {

                            mBuilder.setContentText("下载进度:"+incr+"%");
                            //第一个参数:进度指示器设置为最大值
                            //第二个参数:当前完成百分比
                            //第三个参数:活动指示器启用 如果true 那么会是一个进度展示
                            mBuilder.setProgress(100, incr, true);
                            // 显示进度条
                            notificationManager.notify(tempID, mBuilder.build());

                            try {
                                // 睡眠一段时间,此处应该是你的耗时下载
                                Thread.sleep(1*1000);
                            } catch (InterruptedException e) {
                                Log.d(TAG, "sleep failure");
                            }
                        }
                        //当循环结束后,更新通知,移除 ProgressBar
                        mBuilder.setContentText("下载成功").setProgress(0,0,false);    
                        notificationManager.notify(tempID, mBuilder.build());
                    }
                }
        ).start();
进度显示
五、自定义模式(折叠模式)#####
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        //自定义UI 如果不设置smallIcon不会提示
        builder.setSmallIcon(R.mipmap.ic_launcher);
        builder.setAutoCancel(true);

        //自定义通知栏使用
        RemoteViews remoteViews = new RemoteViews(getPackageName(),R.layout.layout_ui_big);
        //设置TextView的文本
        remoteViews.setTextViewText(R.id.left_tv,"这是左边的文字");
        //设置某个资源,某个资源所使用的方法,该方法的参数
        remoteViews.setInt(R.id.left_tv,"setTextColor",getResources().getColor(R.color.colorAccent));
        remoteViews.setTextViewText(R.id.right_tv,"这是右边的文字");
        //设置某个ImageView的图片
        remoteViews.setImageViewResource(R.id.middle_image,R.drawable.ic_cancel);


        PendingIntent pendingIntent = PendingIntent.getActivity(this,0,new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.baidu.com")),PendingIntent.FLAG_CANCEL_CURRENT);
        remoteViews.setOnClickPendingIntent(R.id.middle_image,pendingIntent);

        builder.setContent(remoteViews);                //默认情况下通知高度为64dp
    
        builder.setCustomBigContentView(remoteViews);   //注意bigContentView 的最大高度是250dp

        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);


        /**
         * builder.setLights(intledARGB ,intledOnMS ,intledOffMS );
         *  android支持三色灯提醒,这个方法就是设置不同场景下的不同颜色的灯。
         *  其中ledARGB 表示灯光颜色、 ledOnMS 亮持续时间、ledOffMS 暗的时间。
         */
        builder.setLights(0xff0000ff, 300, 0);

        /**
         * 设置震动效果 实现效果:延迟0ms,然后振动300ms,在延迟500ms,接着在振动700ms。
         */
        builder.setVibrate(new long[] {0,300,500,700});

        /**
         *  设置声音 builder.setSound(Uri sound);
         *  获取自定义铃声
         *  builder.setSound(Uri.parse("file:///sdcard/xx/xx.mp3"));
         *  获取Android多媒体库内的铃声 数字字符串表示 声音在数据库中的位置
         */
        builder.setSound(Uri.withAppendedPath(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, "5"));

        /**
         * setOngoing(boolean ongoing)
         *
         * 设置该属性true 通知不可滑动删除
         *
         * 功能:设置为ture,表示它为一个正在进行的通知。
         * 他们通常是用来表示一个后台任务,用户积极参与(如播放音乐)或以某种方式正在等待,因此占用设备(如一个文件下载,同步操作,主动网络连接)
         */
        builder.setOngoing(false);


        /**
         * setProgress(int max, int progress,boolean indeterminate)
         * 属性:
         * max:进度条最大数值
         * progress:当前进度、
         * indeterminate:表示进度是否不确定,true为不确定,false为确定
         * 功能:设置带进度条的通知,可以在下载中使用
         */

        // 利用通知管理器去发布通知
        Notification build = builder.build();
        /**
         * 设置标记
         */
        build.flags=Notification.FLAG_AUTO_CANCEL|Notification.DEFAULT_SOUND;


        notificationManager.notify(mNotificationId,builder.build());
折叠时
展开时
六、悬挂式Notification

悬挂式Notification是android5.0新增加的方式,和前两种显示方式不同的是,前两种需要下拉通知栏才能看到通知,而悬挂式Notification不需要下拉通知栏就直接显示出来悬挂在屏幕上方并且焦点不变仍在用户操作的界面因此不会打断用户的操作,过几秒就会自动消失。
和前两种Notification不同的是,他需要调用setFullScreenIntent来将Notification变为悬挂式Notification

//如果描述的PendingIntent已经存在,则在产生新的Intent之前会先取消掉当前的 PendingIntent hangPendingIntent = PendingIntent.getActivity(this, 0, hangIntent, PendingIntent.FLAG_CANCEL_CURRENT);
builder.setFullScreenIntent(hangPendingIntent, true);
Paste_Image.png

实现悬挂式通知完整代码

Notification.Builder builder = new Notification.Builder(this);
Intent mIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://blog.csdn.net/itachi85/"));
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, mIntent, 0);
builder.setContentIntent(pendingIntent);
builder.setSmallIcon(R.drawable.foldleft);
builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.lanucher));
builder.setAutoCancel(true);
builder.setContentTitle("悬挂式通知"); //设置点击跳转 Intent hangIntent = new Intent();
hangIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
hangIntent.setClass(this, MyNotificationActivity.class); //如果描述的PendingIntent已经存在,则在产生新的Intent之前会先取消掉当前的 PendingIntent hangPendingIntent = PendingIntent.getActivity(this, 0, hangIntent, PendingIntent.FLAG_CANCEL_CURRENT);
builder.setFullScreenIntent(hangPendingIntent, true);
notificationManager.notify(2, builder.build());

以上的通知介绍,基本能完成绝大部分的工作需求。
此处借用了的部分内容,大家也可以移步看看该作者写的简书

七、Notification的显示等级

android5.0加入了一种新的模式Notification的显示等级,共有三种:

VISIBILITY_PUBLIC只有在没有锁屏时会显示通知

VISIBILITY_PRIVATE任何情况都会显示通知

VISIBILITY_SECRET在安全锁和没有锁屏的情况下显示通知

设置非常简单只要调用setVisibility方法就可以了

builder.setVisibility(Notification.VISIBILITY_PUBLIC);

我在这里写了个方法来设置Notification等级,用radioGroup来演示Notification的各个显示等级。

private void selectNotofovatiomLevel(Notification.Builder builder) {
        switch (radioGroup.getCheckedRadioButtonId()) {
            case R.id.rb_public:
                builder.setVisibility(Notification.VISIBILITY_PUBLIC);
                builder.setContentText("public");
                break;
            case R.id.rb_private:
                builder.setVisibility(Notification.VISIBILITY_PRIVATE);
                builder.setContentText("private");
                break;
            case R.id.rb_secret:
                builder.setVisibility(Notification.VISIBILITY_SECRET);
                builder.setContentText("secret");
                break;
            default:
                builder.setVisibility(Notification.VISIBILITY_PUBLIC);
                builder.setContentText("public");
                break;

        }
    }

最后部分借鉴至刘望舒
的Android5.x通知应用解析:
http://www.jianshu.com/p/e766ce44268b

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,088评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,715评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,361评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,099评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 60,987评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,063评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,486评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,175评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,440评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,518评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,305评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,190评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,550评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,880评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,152评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,451评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,637评论 2 335

推荐阅读更多精彩内容

  • 原文出处: http://www.androidchina.net/6174.html Notification在...
    木木00阅读 12,270评论 3 32
  • 我们在用手机的时候,如果来了短信,而我们没有点击查看的话,是不是在手机的最上边的状态栏里有一个短信的小图标提示啊?...
    0o失魂鱼o0阅读 753评论 0 2
  • 我没有办法表达自己的声音,我没有自我,我活在小我的世界里,我的小我模仿真我,做一个无我平和的人,她模仿的很好,所以...
    竺子阅读 502评论 0 0
  • 今天看到有亲在好报群里写的文章,如果可以穿越,你想给十年前的自己送什么礼物?作者想送给曾经的自己一个洋娃娃,并且,...
    木木夕cq阅读 228评论 0 0
  • 爱情不就是这样吗? 就在我们是陌生人的时候 多看了一眼对方 就从陌生人变成恋人 在热恋中的我们 总是难舍难分 可我...
    Mixiao阅读 332评论 0 0