安卓组件---Notification 的使用

来源:互联网 发布:超级直播软件apk 编辑:程序博客网 时间:2024/05/20 22:28

一、Notification 的简介

1.1 什么是通知(Notification)

1)文字描述:
通知是一个可以在应用程序正常的用户界面之外显示给用户的消息。
通知发出时,它首先出现在状态栏的通知区域中,用户打开通知抽屉可查看通知详情。通知区域和通知抽屉都是用户可以随时查看的系统控制区域。
作为安卓用户界面的重要组成部分,通知有自己的设计指南。在Android 5.0(API level 21)中引入的 Material Design 的变化是特别重要的,更多信息请阅读 通知设计指南。

1.1 1)图片描述:
这里写图片描述

1.2 Notification的作用

  1. 显示接收到短消息、即使消息等信息 (如QQ、微信、新浪、短信)
  2. 显示客户端的推送消息(如有新版本发布,广告,推荐新闻等)
  3. 显示正在进行的事物(例如:后台运行的程序)(如音乐播放器、版本更新时候的下载进度等)

1.3 通知类型

通知有两种视图:普通视图和大视图。
1、 普通视图:
这里写图片描述
2、 大视图:
这里写图片描述

默认情况下为普通视图,可通过NotificationCompat.Builder.setStyle()设置大视图。

注: 大视图(Big Views)由Android 4.1(API level 16)开始引入,且仅支持Android 4.1及更高版本。
构建大视图通知

以上图为例:
1、构建Action Button的PendingIntent

Intent dismissIntent = new Intent(this, PingService.class);dismissIntent.setAction(CommonConstants.ACTION_DISMISS);PendingIntent piDismiss = PendingIntent.getService(      this, 0, dismissIntent, 0);Intent snoozeIntent = new Intent(this, PingService.class);snoozeIntent.setAction(CommonConstants.ACTION_SNOOZE);PendingIntent piSnooze =       PendingIntent.getService(this, 0, snoozeIntent, 0);

2、构建NotificatonCompat.Builder对象

NotificationCompat.Builder builder =       new NotificationCompat.Builder(this)          .setSmallIcon(R.drawable.ic_stat_notification)          .setContentTitle(getString(R.string.notification))          .setContentText(getString(R.string.ping))          .setDefaults(Notification.DEFAULT_ALL)        // 该方法在Android 4.1之前会被忽略          .setStyle(new NotificationCompat.BigTextStyle()                .bigText(msg))        //添加Action Button        .addAction (R.drawable.ic_stat_dismiss,                getString(R.string.dismiss), piDismiss)        .addAction (R.drawable.ic_stat_snooze,                getString(R.string.snooze), piSnooze);

3、其他步骤与普通视图相同

3 进度条通知

明确进度的进度条
使用setProgress(max, progress, false)来更新进度。
max: 最大进度值
progress: 当前进度
false: 是否是不明确的进度条

模拟下载过程,示例如下:

int id = 1;...mNotifyManager = (NotificationManager)     getSystemService(Context.NOTIFICATION_SERVICE);mBuilder = new NotificationCompat.Builder(this);mBuilder.setContentTitle("Picture Download")    .setContentText("Download in progress")    .setSmallIcon(R.drawable.ic_notification);// Start a lengthy operation in a background threadnew Thread(    new Runnable() {        @Override        public void run() {            int incr;            for (incr = 0; incr <= 100; incr+=5) {                mBuilder.setProgress(100, incr, false);                mNotifyManager.notify(id, mBuilder.build());                try {                    // Sleep for 5 seconds                    Thread.sleep(5*1000);                } catch (InterruptedException e) {                    Log.d(TAG, "sleep failure");                }            }            mBuilder.setContentText("Download complete")//下载完成                               .setProgress(0,0,false);    //移除进度条            mNotifyManager.notify(id, mBuilder.build());        }    }).start();

这里写图片描述

上图,分别为下载过程中进度条通知 和 下载完成移除进度条后的通知。

4 不确定进度的进度条
使用setProgress(0, 0, true)来表示进度不明确的进度条

mBuilder.setProgress(0, 0, true); mNotifyManager.notify(id, mBuilder.build());

这里写图片描述

上图,分别为下载过程中进度条通知 和 下载完成移除进度条后的通知。
5 浮动通知(Heads-up Notifications)

Android 5.0(API level 21)开始,当屏幕未上锁且亮屏时,通知可以以小窗口形式显示。用户可以在不离开当前应用前提下操作该通知。
如图:
这里写图片描述

NotificationCompat.Builder mNotifyBuilder =     new NotificationCompat.Builder(this)        .setContentTitle("New Message")        .setContentText("You've received new messages.")        .setSmallIcon(R.drawable.ic_notify_status)        .setFullScreenIntent(pendingIntent, false);

二、 Notification 的版本及对应创建方法

随着Android系统不断升级,Notification的创建方式也随之变化,主要变化如下:

Android 3.0之前
Android 3.0 (API level 11)之前,使用new Notification()方式创建通知,setLatestEventInfo()函数是唯一的实现方法。前面的有关属性设置这里就不再提了,网上资料很多。:

NotificationManager mNotifyMgr =       (NotificationManager) getSystemService(NOTIFICATION_SERVICE);PendingIntent contentIntent = PendingIntent.getActivity(      this, 0, new Intent(this, ResultActivity.class), 0);Notification notification = new Notification(icon, tickerText, when);notification.setLatestEventInfo(this, title, content, contentIntent);mNotifyMgr.notify(NOTIFICATIONS_ID, notification);

高于Android 3.0 (API level 11)并低于API Level 16 (Android 4.1)版本
高于API Level 11,低于API Level 16 (Android 4.1.2)版本的系统中,可使用Notification.Builder来构造函数。但要使用getNotification()来使notification实现。此时,前面版本在notification中设置的Flags,icon等属性都已经无效,要在builder里面设置

Notification.Builder builder = new Notification.Builder(context)              .setAutoCancel(true)              .setContentTitle("title")              .setContentText("describe")              .setContentIntent(pendingIntent)              .setSmallIcon(R.drawable.ic_launcher)              .setWhen(System.currentTimeMillis())              .setOngoing(true);  notification=builder.getNotification();

高于API Level 16 (Android 4.1)的版本
高于API Level 16的版本,就可以用Builder和build()函数来配套的方便使用notification了。

Notification notification = new Notification.Builder(context)             .setAutoCancel(true)             .setContentTitle("title")             .setContentText("describe")             .setContentIntent(pendingIntent)             .setSmallIcon(R.drawable.ic_launcher)             .setWhen(System.currentTimeMillis())             .build();

Android .LOLLIPOP_MR1(22)以上 也就从6.0开始 只能通过new NotificationCompat.Builder(mContext)

Notification notification = new NotificationCompat.Builder(mContext) .setContentTitle(aInfo.mFilename) .setContentText(contentText) .setSmallIcon(android.R.drawable.stat_sys_download_done) .setContentIntent(pi)// 设置pendingIntent .build();

【注意点】:
1、在构造notification的时候有很多种写法,但是要注意,用
  Notification notification = new Notification();
  这种构建方法的时候,一定要加上notification.icon这个设置,不然,程序虽然不会报错,但是会没有效果。
2、使用了Notification下的setLatestEventInfo()方法时,Eclipse却提示:“ The method setLatestEventInfo(Context, String, String, PendingIntent) is undefined for the type Notification”

2.2 Notification的版本适配

# 综合代码: #     //准备intent     Intent intent = new Intent();      String action = "com.skay.myapp.action";     intent.setAction(action);     //notification      Notification notification = null;      String contentText;      // 构建 PendingIntent      PendingIntent pi = PendingIntent.getActivity(mContext, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);     //版本兼容    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {       notification = new Notification();     notification.icon = android.R.drawable.stat_sys_download_done;     notification.flags |= Notification.FLAG_AUTO_CANCEL;     notification.setLatestEventInfo(mContext, aInfo.mFilename, contentText, pi);    } else if (Build.VERSION.SDK_INT >= 23) {       notification = new NotificationCompat.Builder(mContext)     .setContentTitle(aInfo.mFilename)     .setContentText(contentText)     .setSmallIcon(android.R.drawable.stat_sys_download_done)     .setContentIntent(pi).build();    } else if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN &&      Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP_MR1) {       notification = new Notification.Builder(mContext)     .setAutoCancel(false)     .setContentIntent(pi)     .setSmallIcon(android.R.drawable.stat_sys_download_done)     .setWhen(System.currentTimeMillis())     .build();    }    mNotificationManager.notify(RESULT_ID, notification);

三、 pendingIntent,点击启动Acitvity的相关问题

1、点击后,重复创建Activity
2、传递数据,并需要重新启动 application后进入 activity

四、 自定义布局中按钮等的点击事件的处理

参考文章

http://blog.csdn.net/vipzjyno1/article/details/25248021

http://www.jianshu.com/p/22e27a639787

http://www.cnblogs.com/arture/p/5523695.html

原创粉丝点击