什么是Notification


Notification用于在状态栏显示信息。这些信息一般来源于app的消息推送,或应用的一些功能控制(如播放器)

Notification的两种视图


普通视图

借用官方的图片说明一下Notification视图中包括的内容

1. 内容标题

2. 大图标(Bitmap)

3. 正文内容

4. 附加信息

5. 小图标

6. Notification的推送时间

大视图

除了上图中标出的第7点外,其他的基本和普通视图中的一样。

其中第7点可显示为一下几种内容

1. 显示大图片

在详情区域可以显示一张最大为256dp的图片

2. 显示长文本

在详情区域显示长文本

3. inbox style(因为不知道中文怎样才能说得准确,这里用英文表达)

inbox style在详情区域显示多行文本.

4. 大内容标题

允许用户为扩展视图定义另一个标题。

5. 摘要文本

允许用户在详情区域添加一行额外的文本

创建标准的Notification


以下三项式创建一个标准的Notification的先决条件

1. 小图标, 通过setSmallIcon()方法设置

2. 标题, 通过setContentTitle()方法设置

3. 内容文本, 通过setContentText()方法设置

我们这里不通过调用Notification构造方法的方式创建Notification,因为这种方法已经不推荐使用。

我们使用通过NotificationCompat.Builder类创建Notification。

程序的主布局文本中只有一个id为btnShow的按钮,点击这个按钮显示Notification

package com.whathecode.notificationdemo;import android.app.Notification;
import android.app.NotificationManager;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Button;public class MainActivity extends ActionBarActivity {private Notification mNotification;private NotificationManager mNotificationManager;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Button btnShow = (Button) findViewById(R.id.btnShow);mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);mNotification = new NotificationCompat.Builder(this)// 设置小图标
                .setSmallIcon(R.drawable.ic_launcher)// 设置标题.setContentTitle("you have a meeting")// 设置内容.setContentText("you have a meeting at 3:00 this afternoon").build();btnShow.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {mNotificationManager.notify(0, mNotification);}});}
}

运行效果

当然,这个Demo在4.x系统上是可以正常运行的。

当同样的代码在2.x的系统上面运行,程序会崩溃的。如下

而且,会抛出一个异常:

java.lang.IllegalArgumentException: contentIntent required: pkg=com.whathecode.notificationdemo id=0 notification=Notification(vibrate=null,sound=null,defaults=0x0,flags=0x0)

上面的错误已经说得很清楚了,contentIntent required , 也就是需要contentIntent

这个contentIntent可以通过setContentIntent设置。

也就是说,上面所提到的三个先决条件只是确保4.x版本可以正常运行,

如果你的程序需要兼容2.x版本的,你就需要一个contentIntent

contentIntent的作用是点击Notification时跳转到其他的Activity

更新后的代码:

package com.whathecode.notificationdemo;import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Button;public class MainActivity extends ActionBarActivity {private Notification mNotification;private NotificationManager mNotificationManager;private PendingIntent mResultIntent;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Button btnShow = (Button) findViewById(R.id.btnShow);mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);/** 取得PendingIntent,* 因为我们现在不需要跳转到其他Activity,* 所以这里只实例化一个空的Intent*/Intent intent = new Intent();mResultIntent = PendingIntent.getActivity(this, 1, intent,Intent.FLAG_ACTIVITY_NEW_TASK);mNotification = new NotificationCompat.Builder(this)// 设置小图标
                .setSmallIcon(R.drawable.ic_launcher)// 设置标题.setContentTitle("系统更新")// 设置内容.setContentText("发现系统更新,点击查看详情")//设置ContentIntent
                .setContentIntent(mResultIntent).build();btnShow.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {mNotificationManager.notify(0, mNotification);}});}
}

运行效果

完整的Notification实例


上面代码中的例子并不完整,只是演示了一个可以正常运行的实例

说它不完整是因为Notification到来的时候状态栏只有图标,没有文字,也没有声音提示,用户体验并不好。

当我们不设置LargeIcon的时候,系统就会使用当前设置的小图标作为大图标使用,小图标位置(位置5)则置空。

下面的代码是比较完整的Notification示例

package com.whathecode.notificationdemo;import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.RingtoneManager;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Button;public class MainActivity extends ActionBarActivity {private Notification mNotification;private NotificationManager mNotificationManager;private PendingIntent mResultIntent;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Button btnShow = (Button) findViewById(R.id.btnShow);mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);/** 取得PendingIntent, 并设置跳转到的Activity,*/Intent intent = new Intent(this, UpdateActivity.class);mResultIntent = PendingIntent.getActivity(this, 1, intent,Intent.FLAG_ACTIVITY_NEW_TASK);btnShow.setOnClickListener(new View.OnClickListener() {@SuppressLint("NewApi")@Overridepublic void onClick(View v) {Bitmap largeIcon = BitmapFactory.decodeResource(MainActivity.this.getResources(), R.drawable.luffy);mNotification = new NotificationCompat.Builder(getBaseContext())// 设置大图标
                        .setLargeIcon(largeIcon)// 设置小图标
                        .setSmallIcon(R.drawable.ic_launcher)// 设置小图标旁的文本信息.setContentInfo("1")// 设置状态栏文本标题.setTicker("你的系统有更新")// 设置标题.setContentTitle("系统更新")// 设置内容.setContentText("发现系统更新,点击查看详情")// 设置ContentIntent
                        .setContentIntent(mResultIntent)// 设置Notification提示铃声为系统默认铃声
                        .setSound(RingtoneManager.getActualDefaultRingtoneUri(getBaseContext(),RingtoneManager.TYPE_NOTIFICATION))// 点击Notification的时候使它自动消失.setAutoCancel(true).build();mNotificationManager.notify(0, mNotification);}});}
}

运行效果(Android 2.x)                                                             运行效果(Android 4.x)

                

通过观察上面两张图你会发现,在2.x版本下LargeIcon和contentInfo并没有生效。

这是因为setLargeIcon和setContentInfo都是在api level 11(honeycomb)才添加的功能

使用自定义布局统一Notification的显示效果


布局文件代码

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:background="?android:attr/colorBackground"><ImageViewandroid:id="@+id/largeIcon"android:layout_width="64dp"android:layout_height="64dp"android:src="@drawable/luffy"android:contentDescription="largeIcon" /><TextViewandroid:id="@+id/contentTitle"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_toRightOf="@+id/largeIcon"android:layout_marginLeft="10dp"android:layout_marginTop="5dp"android:text="系统更新"/><TextViewandroid:id="@+id/contentText"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignLeft="@+id/contentTitle"android:layout_below="@+id/contentTitle"android:layout_marginTop="5dp"android:text="发现系统更新,点击查看详情"android:textSize="12sp"/><TextViewandroid:id="@+id/when"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentRight="true"android:layout_marginRight="5dp"android:text="11:00"/><ImageViewandroid:id="@+id/smallIcon"android:layout_width="15dp"android:layout_height="15dp"android:layout_alignRight="@+id/when"android:layout_alignTop="@+id/contentText"android:src="@drawable/ic_launcher" /><TextViewandroid:id="@+id/contentInfo"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignTop="@+id/smallIcon"android:layout_toLeftOf="@+id/smallIcon"android:text="信息"android:textSize="12sp" /></RelativeLayout>

程序代码:

package com.whathecode.notificationdemo;import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.media.RingtoneManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.view.View;
import android.widget.Button;
import android.widget.RemoteViews;public class MainActivity extends Activity {private Notification mNotification;private NotificationManager mNotificationManager;private PendingIntent mResultIntent;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Button btnShow = (Button) findViewById(R.id.btnShow);mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);/** 取得PendingIntent, 并设置跳转到的Activity,*/Intent intent = new Intent(this, UpdateActivity.class);mResultIntent = PendingIntent.getActivity(this, 1, intent,Intent.FLAG_ACTIVITY_NEW_TASK);btnShow.setOnClickListener(new View.OnClickListener() {@SuppressLint("NewApi")@Overridepublic void onClick(View v) {RemoteViews customView = new RemoteViews(getPackageName(),R.layout.customerviews);mNotification = new NotificationCompat.Builder(getBaseContext())// 设置小图标
                        .setSmallIcon(R.drawable.ic_launcher)// 设置状态栏文本标题.setTicker("你的系统有更新")//设置自定义布局
                        .setContent(customView)// 设置ContentIntent
                        .setContentIntent(mResultIntent)// 设置Notification提示铃声为系统默认铃声
                        .setSound(RingtoneManager.getActualDefaultRingtoneUri(getBaseContext(),RingtoneManager.TYPE_NOTIFICATION))// 点击Notification的时候自动移除.setAutoCancel(true).build();/** 当API level 低于14的时候使用setContent()方法是没有用的* 需要对contentView字段直接赋值才能生效*/if (Build.VERSION.SDK_INT < 14) {mNotification.contentView = customView;}mNotificationManager.notify(0, mNotification);}});}
}

上面的布局文件中的内容是硬编码的,也可以通过RemoteViews类中的setXXX方法动态设定内容。

这样程序便更加灵活

运行效果(android 2.x)                                                                             运行效果(android 4.x)

                 

在两个版本中的运行效果基本一样了,但是,在低版本下不是很完美,有部分灰白的地方特别扎眼

网上查了很久也没有找到解决办法,有知道的请告知

更新Notification的内容


因为我们创建的Notification是通过一个Id分别的,因此只要在使用NotificationManager的notify()方法的时候使用

相同的Id就可以更新这个Notification的内容

当然在使用notify()方法之前我们还是要创建一个Notification实例。

转载于:https://www.cnblogs.com/ai-developers/p/4304962.html

状态栏消息提示——使用Notification相关推荐

  1. vue+elementUi在点js.js文件中使用Message消息提示、Notification、MessageBox、succes、import、from

    目录 1.方式一 2.方式二 3.总结 1.方式一 引入 import { Message } from "element-ui"; 使用 Message({message: '请 ...

  2. 13 消息提示 notification 介绍

    Notification: Notification通知可以显示到系统的上方的状态栏(status bar)中. 通知内容的显示分为两个部分: 1.notification area(通知状态栏) 2 ...

  3. Android Notification消息提示

    一般而言,消息提示,可以通过Toast方式,提醒给用户看,而通过Notification方式的话,可以在状态栏显示出来.并且有声音,还有文字描述,并且可以出现在消息公告栏,这在QQ,飞信等常用即时通信 ...

  4. Android实现系统下拉栏的消息提示——Notification

    Android实现系统下拉栏的消息提示--Notification 系统默认样式 默认通知(通用) 效果图 按钮 <Button android:layout_width="match ...

  5. 最好用的 6 款 Vue 实时消息提示通知(Message/Notification)组件推荐与测评

    本文完整版:<最好用的 6 款 Vue 实时消息提示通知(Message/Notification)组件推荐与测评> Vue 实时消息提示通知 Vue-notification - 专注实 ...

  6. 【Android】消息提示notification

    notification 1.notification消息提示 由Android系统来管理和维护的,因此用户可以随时进入查看.某些信息不需要用户马上处理,可以利用通知,即延迟消息,比如软件的更新.短信 ...

  7. Android安卓——消息提示

    Android系统提供一套友好的消息提示机制,不会打断用户当前的操作. 在安卓应用中最常见的就是消息的提示,而消息的提示有多种方式,可根据实际的需要来选择使用. 本次介绍Toast提示框.Notifi ...

  8. android应用消息,Android学习笔记(05)——Android应用程序的三种消息提示(通知方式)...

    Android有三种消息提示方式,分别是:状态栏通知.对话框通知和吐西(Toast)通知,下面记录这三种不同方式的用法以及区别: 一.状态栏通知(Notification) 通知用于在状态栏显示消息, ...

  9. android11通知栏按钮,android开发(11) 消息栏通知(Notification)

    android 的消息通知还是很方便的,它会出现在窗体的顶部,并给出提示.常见的短信就是这样的通知方式.本文我们尝试实现一个这样的演示. 演示截图: 实现步骤: 1.获得NotificationMan ...

最新文章

  1. Uva1600 巡逻机器人
  2. Python入门100题 | 第009题
  3. 《OKR源于英特尔和谷歌的目标管理利器》读书笔记
  4. 30年职场生涯的感悟[转]
  5. virtual function的一些心得
  6. Floyd求传递闭包
  7. 强化学习-动态规划_强化学习-第5部分
  8. 关于C#异步编程你应该了解的几点建议
  9. 映世便携音箱我对你一见钟情啦~
  10. springboot+mybatis+mysql(增删改查xml入门编程)
  11. sybase:SQL Exception and Warning Messages大全
  12. 2021年宇华实验中学高考成绩查询,2021年河南高考状元多少分,今年河南高考状元资料名单...
  13. macosx安装之旅(1)-硬盘安装
  14. 交易系统典藏书籍总汇以及系统交易、程序化交易等经典资料收藏
  15. DataFrame计算corr()函数计算相关系数时,出现返回值为空或NaN的情况+np.log1p()
  16. warning: control reaches end of non-void function(C语言编译报错)
  17. 看完不会你揍我!!Pytorch利用文本数据建立自己的数据集- Dataset Dataloader详解 附案例
  18. 解决ubuntu16.04插耳机没有声音的问题
  19. 压缩或解压文件出现循环冗余检查的解决办法
  20. 解决pytorch当中RuntimeError: expected scalar type Double but found Float的问题

热门文章

  1. 雨量、阳光、防雾传感器
  2. DevOps - Spring Boot自动部署到WebLogic
  3. 如何利用WebScarab绕过JS验证
  4. hdu 1728 逃离迷宫 (bfs)
  5. 2011年7月28日星期四精彩网语
  6. [浪子学编程][MS Enterprise Library]ObjectBuilder之创建策略祥解(一)
  7. 实验8-SPSS交叉表分析
  8. .net通过获取客户端IP地址反查出用户的计算机名
  9. Handler消息处理机制
  10. Two ways to assign values to member variables