在消息通知时,我们经常用到两个组件Toast和Notification。特别是重要的和需要长时间显示的信息,用Notification就最合适不过了。当有消息通知时,状态栏会显示通知的图标和文字,通过下拉状态栏,就可以看到通知信息了,Android这一创新性的UI组件赢得了用户的一致好评,就连苹果也开始模仿了。今天我们就结合实例,探讨一下Notification具体的使用方法。

首先说明一下我们需要实现的功能是:在程序启动时,发出一个通知,这个通知在软件运行过程中一直存在,相当于qq的托盘一样;然后再演示一下普通的通知和自定义视图通知。

那我们就先建立一个名为notification的项目,然后编辑/res/layout/main.xml文件,代码如下:

[html] view plaincopyprint?
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:orientation="vertical"
  4. android:layout_width="fill_parent"
  5. android:layout_height="fill_parent">
  6. <TextView
  7. android:layout_width="fill_parent"
  8. android:layout_height="wrap_content"
  9. android:gravity="center"
  10. android:text="点击按钮进入演示界面"/>
  11. <Button
  12. android:layout_width="fill_parent"
  13. android:layout_height="wrap_content"
  14. android:text="notify activity"
  15. android:onClick="notify"/>
  16. </LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical"android:layout_width="fill_parent"android:layout_height="fill_parent"><TextViewandroid:layout_width="fill_parent"android:layout_height="wrap_content"android:gravity="center"android:text="点击按钮进入演示界面"/><Buttonandroid:layout_width="fill_parent"android:layout_height="wrap_content"android:text="notify activity"android:onClick="notify"/>
</LinearLayout>

然后编辑MainActivity.java文件,代码如下:

[java] view plaincopyprint?
  1. package com.scott.notification;
  2. import android.app.Activity;
  3. import android.app.Notification;
  4. import android.app.NotificationManager;
  5. import android.app.PendingIntent;
  6. import android.content.Context;
  7. import android.content.Intent;
  8. import android.os.Bundle;
  9. import android.view.View;
  10. public class MainActivity extends Activity {
  11. private static final int ONGOING_ID = 0;
  12. private NotificationManager mNotificationManager;
  13. @Override
  14. public void onCreate(Bundle savedInstanceState) {
  15. super.onCreate(savedInstanceState);
  16. setContentView(R.layout.main);
  17. setUpNotification();
  18. }
  19. private void setUpNotification() {
  20. Context context = this;
  21. mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
  22. int icon = R.drawable.ongoing;
  23. CharSequence tickerText = "程序已启动";
  24. long when = System.currentTimeMillis();
  25. //新建一个Notification实例
  26. Notification notification = new Notification(icon, tickerText, when);
  27. // 把通知放置在"正在运行"栏目中
  28. notification.flags |= Notification.FLAG_ONGOING_EVENT;
  29. CharSequence contentTitle = "Notification示例";
  30. CharSequence contentText = "程序正在运行中,点击此处跳到演示界面";
  31. Intent intent = new Intent(context, NotifyActivity.class);
  32. PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent, 0);
  33. notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
  34. mNotificationManager.notify(ONGOING_ID, notification);
  35. }
  36. public void notify(View view) {
  37. Intent intent = new Intent(this, NotifyActivity.class);
  38. startActivity(intent);
  39. }
  40. @Override
  41. public void onBackPressed() {
  42. super.onBackPressed();
  43. finish();
  44. //取消一个通知
  45. mNotificationManager.cancel(ONGOING_ID);
  46. //结束进程
  47. android.os.Process.killProcess(android.os.Process.myPid());
  48. System.exit(0);
  49. }
  50. }
package com.scott.notification;import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;public class MainActivity extends Activity {private static final int ONGOING_ID = 0;private NotificationManager mNotificationManager;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);setUpNotification();}private void setUpNotification() {Context context = this;mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);int icon = R.drawable.ongoing;CharSequence tickerText = "程序已启动";long when = System.currentTimeMillis();//新建一个Notification实例Notification notification = new Notification(icon, tickerText, when);// 把通知放置在"正在运行"栏目中notification.flags |= Notification.FLAG_ONGOING_EVENT;CharSequence contentTitle = "Notification示例";CharSequence contentText = "程序正在运行中,点击此处跳到演示界面";Intent intent = new Intent(context, NotifyActivity.class);PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent, 0);notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);mNotificationManager.notify(ONGOING_ID, notification);}public void notify(View view) {Intent intent = new Intent(this, NotifyActivity.class);startActivity(intent);}@Overridepublic void onBackPressed() {super.onBackPressed();finish();//取消一个通知mNotificationManager.cancel(ONGOING_ID);//结束进程android.os.Process.killProcess(android.os.Process.myPid());System.exit(0);}
}

大家看以看到,在程序主界面启动时会发出一个通知,并且将这个通知放置在“正在运行”栏目中,这样在软件运行过程中它就会始终存在;另外,在上面的代码中,在用户按下回退按钮时,我们使用NotificationManager.cancel(int id)方法取消这个通知。

先来看一下运行效果如何:

点击主界面的按钮和Ongoing栏目中的通知均能跳转到NotifyActivity界面,在这个界面中,我们主要演示一下普通通知和自定义视图通知的使用。

我们先要在/res/layout/目录下添加一个notify.xml布局文件,代码如下:

[html] view plaincopyprint?
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:orientation="vertical"
  4. android:layout_width="fill_parent"
  5. android:layout_height="fill_parent">
  6. <Button
  7. android:layout_width="fill_parent"
  8. android:layout_height="wrap_content"
  9. android:text="normal notify"
  10. android:onClick="normalNotify"/>
  11. <Button
  12. android:layout_width="fill_parent"
  13. android:layout_height="wrap_content"
  14. android:text="custom notify"
  15. android:onClick="customNotify"/>
  16. </LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical"android:layout_width="fill_parent"android:layout_height="fill_parent"><Buttonandroid:layout_width="fill_parent"android:layout_height="wrap_content"android:text="normal notify"android:onClick="normalNotify"/><Buttonandroid:layout_width="fill_parent"android:layout_height="wrap_content"android:text="custom notify"android:onClick="customNotify"/>
</LinearLayout>

因为要演示自定义通知视图,我们需要定义一个自定义通知视图的布局文件,摆放我们自己的布局组件,因此在/res/layout/目录下添加一个custom_notification_layout.xml文件,代码如下:

[html] view plaincopyprint?
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:orientation="horizontal"
  4. android:layout_width="fill_parent"
  5. android:layout_height="fill_parent"
  6. android:padding="3dp">
  7. <ImageView
  8. android:id="@+id/imageView"
  9. android:layout_width="wrap_content"
  10. android:layout_height="fill_parent"
  11. android:layout_marginRight="10dp"/>
  12. <TextView
  13. android:id="@+id/textView"
  14. android:layout_width="wrap_content"
  15. android:layout_height="fill_parent"
  16. android:textColor="#000"/>
  17. </LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="horizontal"android:layout_width="fill_parent"android:layout_height="fill_parent"android:padding="3dp"><ImageViewandroid:id="@+id/imageView"android:layout_width="wrap_content"android:layout_height="fill_parent"android:layout_marginRight="10dp"/><TextView android:id="@+id/textView"         android:layout_width="wrap_content"              android:layout_height="fill_parent"              android:textColor="#000"/>
</LinearLayout>

然后就来看一下NotifyActivity.java的代码:

[java] view plaincopyprint?
  1. package com.scott.notification;
  2. import android.app.Activity;
  3. import android.app.Notification;
  4. import android.app.NotificationManager;
  5. import android.app.PendingIntent;
  6. import android.content.Context;
  7. import android.content.Intent;
  8. import android.os.Bundle;
  9. import android.view.View;
  10. import android.widget.RemoteViews;
  11. public class NotifyActivity extends Activity {
  12. //注意,如果不想覆盖前一个通知,需设置不同的ID
  13. private static final int NORMAL_NOTIFY_ID = 1;
  14. private static final int CUSTOM_NOTIFY_ID = 2;
  15. @Override
  16. protected void onCreate(Bundle savedInstanceState) {
  17. super.onCreate(savedInstanceState);
  18. setContentView(R.layout.notify);
  19. }
  20. // 普通通知事件
  21. public void normalNotify(View view) {
  22. Context context = this;
  23. NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
  24. int icon = android.R.drawable.stat_notify_voicemail;
  25. CharSequence tickerText = "普通通知";
  26. long when = System.currentTimeMillis();
  27. Notification notification = new Notification(icon, tickerText, when);
  28. // 设定声音
  29. notification.defaults |= Notification.DEFAULT_SOUND;
  30. //设定震动(需加VIBRATE权限)
  31. notification.defaults |= Notification.DEFAULT_VIBRATE;
  32. // 设定LED灯提醒
  33. notification.defaults |= Notification.DEFAULT_LIGHTS;
  34. // 设置点击此通知后自动清除
  35. notification.flags |= Notification.FLAG_AUTO_CANCEL;
  36. CharSequence contentTitle = "普通通知的标题";
  37. CharSequence contentText = "通知的内容部分,一段长长的文字...";
  38. Intent intent = new Intent(context, TargetActivity.class);
  39. PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent, 0);
  40. notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
  41. mNotificationManager.notify(NORMAL_NOTIFY_ID, notification);
  42. }
  43. // 个性化通知点击事件
  44. public void customNotify(View view) {
  45. Context context = this;
  46. NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
  47. int icon = android.R.drawable.stat_notify_voicemail;
  48. CharSequence tickerText = "自定义通知";
  49. long when = System.currentTimeMillis();
  50. Notification notification = new Notification(icon, tickerText, when);
  51. notification.flags |= Notification.FLAG_AUTO_CANCEL;
  52. RemoteViews contentView = new RemoteViews(context.getPackageName(), R.layout.custom_notification_layout);
  53. contentView.setImageViewResource(R.id.imageView, R.drawable.smile);
  54. contentView.setTextViewText(R.id.textView, "这是一个个性化的通知视图,代替了系统默认的通知视图.");
  55. // 指定个性化视图
  56. notification.contentView = contentView;
  57. Intent intent = new Intent(context, TargetActivity.class);
  58. PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent, 0);
  59. // 指定内容意图
  60. notification.contentIntent = contentIntent;
  61. mNotificationManager.notify(CUSTOM_NOTIFY_ID, notification);
  62. }
  63. }
package com.scott.notification;import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.RemoteViews;public class NotifyActivity extends Activity {//注意,如果不想覆盖前一个通知,需设置不同的IDprivate static final int NORMAL_NOTIFY_ID = 1;private static final int CUSTOM_NOTIFY_ID = 2;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.notify);}// 普通通知事件public void normalNotify(View view) {Context context = this;NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);int icon = android.R.drawable.stat_notify_voicemail;CharSequence tickerText = "普通通知";long when = System.currentTimeMillis();Notification notification = new Notification(icon, tickerText, when);// 设定声音notification.defaults |= Notification.DEFAULT_SOUND;//设定震动(需加VIBRATE权限)notification.defaults |= Notification.DEFAULT_VIBRATE;// 设定LED灯提醒notification.defaults |= Notification.DEFAULT_LIGHTS;// 设置点击此通知后自动清除notification.flags |= Notification.FLAG_AUTO_CANCEL;CharSequence contentTitle = "普通通知的标题";CharSequence contentText = "通知的内容部分,一段长长的文字...";Intent intent = new Intent(context, TargetActivity.class);PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent, 0);notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);mNotificationManager.notify(NORMAL_NOTIFY_ID, notification);}// 个性化通知点击事件public void customNotify(View view) {Context context = this;NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);int icon = android.R.drawable.stat_notify_voicemail;CharSequence tickerText = "自定义通知";long when = System.currentTimeMillis();Notification notification = new Notification(icon, tickerText, when);notification.flags |= Notification.FLAG_AUTO_CANCEL;RemoteViews contentView = new RemoteViews(context.getPackageName(), R.layout.custom_notification_layout);contentView.setImageViewResource(R.id.imageView, R.drawable.smile);contentView.setTextViewText(R.id.textView, "这是一个个性化的通知视图,代替了系统默认的通知视图.");// 指定个性化视图notification.contentView = contentView;Intent intent = new Intent(context, TargetActivity.class);PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent, 0);// 指定内容意图notification.contentIntent = contentIntent;mNotificationManager.notify(CUSTOM_NOTIFY_ID, notification);}
}

注意,上边在添加一个普通通知时使用到了震动,所以需要在AndroidManifest.xml中加入相关权限:

[html] view plaincopyprint?
  1. <uses-permission android:name="android.permission.VIBRATE"/>
<uses-permission android:name="android.permission.VIBRATE"/>

除了使用代码中的默认通知属性之外,用户也可以自定义属性值:

1.自定义声音:

[java] view plaincopyprint?
  1. notification.sound = Uri.parse("file:///sdcard/notification/ringer.mp3");
notification.sound = Uri.parse("file:///sdcard/notification/ringer.mp3");

2.自定义震动方式:

[java] view plaincopyprint?
  1. long[] vibrate = {0, 100, 200, 300};
  2. notification.vibrate = vibrate;
long[] vibrate = {0, 100, 200, 300};
notification.vibrate = vibrate;

这个数组定义了交替的震动和关闭,以毫秒为单位。第一个值是等待多久开始震动,第二个值是第一次震动的时间,第三个值是停止震动的时间,以此类推。定义多长时间都行,但是不能设置为重复。

3.自定义闪光方式:

[java] view plaincopyprint?
  1. notification.ledARGB = 0xff00ff00;
  2. notification.ledOnMS = 300;
  3. notification.ledOffMS = 1000;
  4. notification.flags |= Notification.FLAG_SHOW_LIGHTS;
notification.ledARGB = 0xff00ff00;
notification.ledOnMS = 300;
notification.ledOffMS = 1000;
notification.flags |= Notification.FLAG_SHOW_LIGHTS;

上边几行代码表示绿灯先显示300毫秒然后关闭一秒钟。如果设备不支持指定的颜色,则会按照最接近的颜色显示。

如果全部都使用默认值时,可以用以下代码代替程序中的几行设定defaults的代码:

[java] view plaincopyprint?
  1. notification.defaults |= Notification.DEFAULT_ALL;
notification.defaults |= Notification.DEFAULT_ALL;

注意,在自定义以上属性时,如果defaults中与之相关的默认值已设置,则自定义属性就会失效。

然后再来介绍一下几种常用的flags:

1.FLAG_AUTO_CANCEL:在用户查看通知信息后自动关闭通知;

2.FLAG_INSISTENT:在用户响应之前一直重复;

3.FLAG_ONGOING_EVENT:放置在“正在运行”栏目中,表示程序正在运行,可见状态,或是后台运行;

4.FLAG_NO_CLEAR:查看通知后不会自动取消,对一直进行中的通知非常有用。

在上面的程序中,点击通知后跳转到TargetActivity界面,这个界面非常简单,就显示一串文字,这里就不必多说了。

最后让我们演示一下效果:

关于notification的相关知识,今天先介绍到这里,以后会继续介绍更深入的使用技巧。

<!-- Baidu Button BEGIN -->

Notification使用详解之一:基础应用相关推荐

  1. Notification使用详解之三:通过服务更新进度通知在Activity中监听服务进度

    为什么80%的码农都做不了架构师?>>>    上次我们讲到如何实现一个可更新的进度通知,实现的方式是启动一个线程模拟一个下载任务,然后根据任务进度向UI线程消息队列发送进度消息,U ...

  2. Android Notification通知详解

    Android Notification通知详解 Notification: (一).简介: 显示在手机状态栏的通知.Notification所代表的是一种具有全局效果的通知,程序一般通过Notifi ...

  3. 完全手册-MATLAB使用详解:基础、开发及工程应用

    [书名]完全手册-MATLAB使用详解:基础.开发及工程应用 [作者]董霖 编著 [ISBN]978-7-121-07397-7 [出版社]电子工业出版社 [出版日期]2009年1月 [内容简介] M ...

  4. Python|线程和进程|阻塞|非阻塞|同步|异步|生成器和协程|资源竞争|进程间通信|aiohttp库|daemon属性值详解|语言基础50课:学习(11)

    文章目录 系列目录 原项目地址 第34课:Python中的并发编程-1 线程和进程 多线程编程 使用 Thread 类创建线程对象 继承 Thread 类自定义线程 使用线程池 守护线程 资源竞争 G ...

  5. Java方法详解(基础)

    Java方法详解(基础) 什么是方法? System.out.println():调用系统类标准输出对象方法out. 方法是语句的集合,他们在一起执行一个功能. 方法是解决一类问题的步骤的有序组合. ...

  6. 用于生成随机数的python标准库模块是_详解Python基础random模块随机数的生成

    详解Python基础random模块随机数的生成 来源:中文源码网    浏览: 次    日期:2019年11月5日 [下载文档:  详解Python基础random模块随机数的生成.txt ] ( ...

  7. [翻译]拒绝服务***详解之基础篇

    [翻译]拒绝服务***详解之基础篇 本帖被 EvilOctal 从 论坛原创{ Original Paper } 移动到本区(2007-03-19) Constantly 51cto技术博客 Cons ...

  8. 最简单太阳系H5动画canvas详解 零基础可入

    最简单太阳系H5动画canvas详解 零基础可入 最终结果:(实际为动画效果,金星绕轨道转动) 页面准备/html 要使用canvas,需要首先在页面中要绘制的位置放入canvas标签元素,在后期的绘 ...

  9. Notification使用详解之四:由后台服务向Activity发送进度信息

    上次讲到了如何在Activity中监听后台服务的进度信息,实现的方式是让Activity与后台服务绑定,通过中间对象Binder的实例操作后台服务.从效果上来讲,这种方式是可行的,不过这种实现有个缺点 ...

  10. java jdbc_详解Java基础知识——JDBC

    JDBC Java DataBase Connectivity,java数据库连接,为了降低操作数据的难度,java提供jdbc,按照java面向对象特点,对操作进行了很多封装. JDBC提供了很多接 ...

最新文章

  1. 2021入门推荐系统,应该从哪入手?
  2. Wisdom RESTClient支持自动化测试并可以生成API文档
  3. sqlite java需要按照,SQLite:java/jdbsqlite和python/sqlite3的区别
  4. boost::proto::make_expr相关的测试程序
  5. matlab搭建sdn,软件定义网络SDN简介和简单仿真实验
  6. java 切面_Java笔试面试精心整理得到89道Spring 核心知识【收藏向】
  7. erlang 程序设计书中的错误
  8. shell脚本 猜数字游戏并计数比较次数
  9. 一用户使用LTC以168万美元的价格购入收藏界“圣杯“卡片
  10. unity中使用本地数据库sqlite
  11. SpringBoot配置多数据源(动态切换)
  12. Java二进制的符号位在哪一位_Java位运算符及二进制常识
  13. 计算机专业的英文简历范文带翻译,英文个人简历带翻译【英文简历范文带翻译】...
  14. java自动机字符串匹配_【算法】利用有限自动机进行字符串匹配
  15. CAD快速测量面积与周长
  16. SourceTree Push 代码报错:remote: Support for password authentication was removed on April 26, 2022....
  17. 开一间煎饼果子店能挣多少钱?
  18. Java集合的subList方法分析
  19. java过滤_java 过滤list的几种方式
  20. Manjaro手动调节屏幕亮度

热门文章

  1. 《Java8实战》-第五章读书笔记(使用流Stream-02)
  2. CentOS7 系统升级,删除centos7开机界面多余选,升级至最新的内核
  3. 外链应该这样发,网站排名速度提升十陪
  4. 黑客观察手机倾斜角度就能猜出你的密码,首次命中率高达74%!
  5. 根据输入网络服务名称取得端口号
  6. 局域网arp欺骗病毒查找预防方法(1)
  7. 【Absible学习】Ansible普通用户sudo执行指令
  8. 初探 Go 的编译命令执行过程
  9. 从智慧信号灯看智能城市管理
  10. Leetcode题目:Lowest Common Ancestor of a Binary Search Tree