Notification使用详解之一:基础应用

Stella981
• 阅读 603

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

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

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

[html] view plain copy

  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. android:orientation="vertical"
  3. android:layout_width="fill_parent"
  4. android:layout_height="fill_parent">
  5. <TextView
  6. android:layout_width="fill_parent"
  7. android:layout_height="wrap_content"
  8. android:gravity="center"
  9. android:text="点击按钮进入演示界面"/>
  10. <Button
  11. android:layout_width="fill_parent"
  12. android:layout_height="wrap_content"
  13. android:text="notify activity"
  14. android:onClick="notify"/>
  15. </LinearLayout>

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

[java] view plain copy

  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. }

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

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

Notification使用详解之一:基础应用

Notification使用详解之一:基础应用

Notification使用详解之一:基础应用

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

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

[html] view plain copy

  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. android:orientation="vertical"
  3. android:layout_width="fill_parent"
  4. android:layout_height="fill_parent">
  5. <Button
  6. android:layout_width="fill_parent"
  7. android:layout_height="wrap_content"
  8. android:text="normal notify"
  9. android:onClick="normalNotify"/>
  10. <Button
  11. android:layout_width="fill_parent"
  12. android:layout_height="wrap_content"
  13. android:text="custom notify"
  14. android:onClick="customNotify"/>
  15. </LinearLayout>

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

[html] view plain copy

  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. android:orientation="horizontal"
  3. android:layout_width="fill_parent"
  4. android:layout_height="fill_parent"
  5. android:padding="3dp">
  6. <ImageView
  7. android:id="@+id/imageView"
  8. android:layout_width="wrap_content"
  9. android:layout_height="fill_parent"
  10. android:layout_marginRight="10dp"/>
  11. <TextView
  12. android:id="@+id/textView"
  13. android:layout_width="wrap_content"
  14. android:layout_height="fill_parent"
  15. android:textColor="#000"/>
  16. </LinearLayout>

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

[java] view plain copy

  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. }

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

[html] view plain copy

  1. <uses-permission android:name="android.permission.VIBRATE"/>

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

1.自定义声音:

[java] view plain copy

  1. notification.sound = Uri.parse("file:///sdcard/notification/ringer.mp3");

2.自定义震动方式:

[java] view plain copy

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

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

3.自定义闪光方式:

[java] view plain copy

  1. notification.ledARGB = 0xff00ff00;
  2. notification.ledOnMS = 300;
  3. notification.ledOffMS = 1000;
  4. notification.flags |= Notification.FLAG_SHOW_LIGHTS;

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

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

[java] view plain copy

  1. notification.defaults |= Notification.DEFAULT_ALL;

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

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

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

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

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

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

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

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

Notification使用详解之一:基础应用  Notification使用详解之一:基础应用

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

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Wesley13 Wesley13
2年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
2年前
Java日期时间API系列36
  十二时辰,古代劳动人民把一昼夜划分成十二个时段,每一个时段叫一个时辰。二十四小时和十二时辰对照表:时辰时间24时制子时深夜11:00凌晨01:0023:0001:00丑时上午01:00上午03:0001:0003:00寅时上午03:00上午0
Wesley13 Wesley13
2年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
2年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Stella981 Stella981
2年前
JOptionPane修改图标
1.在Linux平台下.JOptionPane会显示Java默认的图标,在window平台不显示图标,如何替换这个图标了?2JOptionPane.setIcon(Icon)修改的是内容区域的icon,而不是左上角的Icon.所以需要通过修改Jdialog/Frame的图标来达到修改默认图标的问题.3.代码:if(JOptio
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
3个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这