展会信息港展会大全

Android开发之通知栏Notification详解
来源:互联网   发布日期:2015-10-02 21:44:19   浏览:1742次  

导读:Notification的用法 --- 状态栏通知发送一个状态栏通知必须的两个类:1. NotificationManager --- 状态栏通知的管理类,负责发通知,清除通知等 ...

Notification的用法--- 状态栏通知

发送一个状态栏通知必须的两个类:

1. NotificationManager--- 状态栏通知的管理类,负责发通知,清除通知等

NotificationManager : 是一个系统Service,必须通过 context.getSystemService(NOTIFICATION_SERVICE)方法获取

NotificationManager notificationManager = (NotificationManager) context.getSystemService(android.content.Context.NOTIFICATION_SERVICE);

2.Notification--- 具体的状态栏通知对象,可以设置icon,文字,提示音,震动等参数

下面是设置一个通知需要的基本参数

Anicon(通知的图标)

Atitleanexpandedmessage(通知的标题和内容)

APendingIntent(点击通知执行页面跳转)

1.创建Notification

通过NotificationManager的notify(int Id , Notification)方法来启动Notification

参数一:Notification的唯一标识

参数二:Notification对象

2.更新Notification

调用Notification的setLatestEventInfo()方法来更新内容,然后调用NotificationManager的notify()方法即可

3.删除Notification

通过NotificationManager的cancle(int id) 方法,清除通知参数: 要清除的Notification的唯一标识

4.Notification设置-- 震动,铃声等

1.基本设置:

//新建状态栏通知

baseNF=new Notification();

//设置通知在状态栏显示的图标

baseNF.icon=R.drawable.icon;

//通知时在状态栏显示的内容

baseNF.tickerText="YouclickedBaseNF!";

//通知的默认参数DEFAULT_SOUND,DEFAULT_VIBRATE,DEFAULT_LIGHTS.

//如果要全部采用默认值,用DEFAULT_ALL.

//此处采用默认声音

baseNF.defaults=Notification.DEFAULT_SOUND;

//第二个参数:下拉状态栏时显示的消息标题expandedmessagetitle

//第三个参数:下拉状态栏时显示的消息内容expandedmessagetext

//第四个参数:点击该通知时执行页面跳转

baseNF.setLatestEventInfo(Lesson_10.this,"Title01","Content01",pd);

//发出状态栏通知

//ThefirstparameteristheuniqueIDfortheNotification

//andthesecondistheNotificationobject.

nm.notify(Notification_ID_BASE,baseNF);

2.添加声音

baseNF.default=Notification.DEFAULT_SOUND;-- 使用系统默认提示音

notification.sound=Uri.parse("file:///sdcard/notification/ringer.mp3");--- 自定义声音

使用用系统自带的铃声,可以这样:

notification.sound=Uri.withAppendedPath(Audio.Media.INTERNAL_CONTENT_URI,"6");

3.添加震动

notification.defaults|=Notification.DEFAULT_VIBRATE;使用默认震动方式

4.添加闪光

notification.defaults|=Notification.DEFAULT_LIGHTS;

5.其他有用的设置:

flags:

Notification.FLAG_INSISTENT;//让声音、振动无限循环,直到用户响应

Notification.FLAG_AUTO_CANCEL;//通知被点击后,自动消失

Notification.FLAG_NO_CLEAR;//点击'Clear'时,不清楚该通知(QQ的通知无法清除,就是用的这个

//自定义下拉视图,比如下载软件时,显示的进度条。

Notificationnotification=newNotification();

notification.icon=R.drawable.icon;

notification.tickerText="Custom!";

RemoteViewscontentView=newRemoteViews(getPackageName(),R.layout.custom);

contentView.setImageViewResource(R.id.image,R.drawable.icon);

contentView.setTextViewText(R.id.text,"Hello,thismessageisinacustomexpandedview");

notification.contentView=contentView;

//使用自定义下拉视图时,不需要再调用setLatestEventInfo()方法

//但是必须定义contentIntent

notification.contentIntent=pd;

nm.notify(3,notification);

应用实例一:

根据activity的生命周期,在activity不显示时,会执行onStop函数(比如按下home键),所以你在onStop函数(按退出键除外)里面把notification放在通知栏里,再此显示时,把notification从通知栏里去掉。或者,只要程序在运行就一直显示通知栏图标。

下面对Notification类中的一些常量,字段,方法简单介绍一下:

常量:

DEFAULT_ALL使用所有默认值,比如声音,震动,闪屏等等

DEFAULT_LIGHTS 使用默认闪光提示

DEFAULT_SOUNDS 使用默认提示声音

DEFAULT_VIBRATE 使用默认手机震动

【说明】:加入手机震动,一定要在manifest.xml中加入权限:

以上的效果常量可以叠加,即通过

notification.defaults =DEFAULT_SOUND|DEFAULT_VIBRATE;

notification.defaults |= DEFAULT_SOUND (最好在真机上测试,震动效果模拟器上没有)

//设置flag位

FLAG_AUTO_CANCEL该通知能被状态栏的清除按钮给清除掉

FLAG_NO_CLEAR该通知能被状态栏的清除按钮给清除掉

FLAG_ONGOING_EVENT 通知放置在正在运行

FLAG_INSISTENT 是否一直进行,比如音乐一直播放,知道用户响应

常用字段:

contentIntent设置PendingIntent对象,点击时发送该Intent

defaults 添加默认效果

flags 设置flag位,例如FLAG_NO_CLEAR等

icon 设置图标

sound 设置声音

tickerText 显示在状态栏中的文字

when 发送此通知的时间戳

NotificationManager常用方法介绍:

public void cancelAll() 移除所有通知(只是针对当前Context下的Notification)

publicvoid cancel(int id) 移除标记为id的通知 (只是针对当前Context下的所有Notification)

publicvoid notify(String tag ,int id, Notification notification) 将通知加入状态栏,标签为tag,标记为id

publicvoid notify(int id, Notification notification) 将通知加入状态栏,标记为id

package com.ljq.activity;

import android.app.Activity;

import android.app.Notification;

import android.app.NotificationManager;

import android.app.PendingIntent;

import android.content.Intent;

import android.graphics.Color;

import android.os.Bundle;

public class MainActivity extends Activity {

/** Called when the activity is first created. */

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

clearNotification();

}

@Override

protected void onStop() {

showNotification();

super.onStop();

}

@Override

protected void onStart() {

clearNotification();

super.onStart();

}

/**

* 在状态栏显示通知

*/

private void showNotification(){

// 创建一个NotificationManager的引用

NotificationManager notificationManager = (NotificationManager)

this.getSystemService(android.content.Context.NOTIFICATION_SERVICE);

// 定义Notification的各种属性

Notification notification =new Notification(R.drawable.icon,

"督导系统", System.currentTimeMillis());

//FLAG_AUTO_CANCEL该通知能被状态栏的清除按钮给清除掉

//FLAG_NO_CLEAR该通知不能被状态栏的清除按钮给清除掉

//FLAG_ONGOING_EVENT 通知放置在正在运行

//FLAG_INSISTENT是否一直进行,比如音乐一直播放,知道用户响应

notification.flags |= Notification.FLAG_ONGOING_EVENT; // 将此通知放到通知栏的"Ongoing"即"正在运行"组中

notification.flags |= Notification.FLAG_NO_CLEAR; // 表明在点击了通知栏中的"清除通知"后,此通知不清除,经常与FLAG_ONGOING_EVENT一起使用

notification.flags |= Notification.FLAG_SHOW_LIGHTS;

//DEFAULT_ALL使用所有默认值,比如声音,震动,闪屏等等

//DEFAULT_LIGHTS使用默认闪光提示

//DEFAULT_SOUNDS使用默认提示声音

//DEFAULT_VIBRATE 使用默认手机震动,需加上权限

notification.defaults = Notification.DEFAULT_LIGHTS;

//叠加效果常量

//notification.defaults=Notification.DEFAULT_LIGHTS|Notification.DEFAULT_SOUND;

notification.ledARGB = Color.BLUE;

notification.ledOnMS =5000; //闪光时间,毫秒

// 设置通知的事件消息

CharSequence contentTitle ="督导系统标题"; // 通知栏标题

CharSequence contentText ="督导系统内容"; // 通知栏内容

Intent notificationIntent =new Intent(MainActivity.this, MainActivity.class); // 点击该通知后要跳转的Activity

PendingIntent contentItent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

notification.setLatestEventInfo(this, contentTitle, contentText, contentItent);

// 把Notification传递给NotificationManager

notificationManager.notify(0, notification);

}

?

//删除通知

private void clearNotification(){

// 启动后删除之前我们定义的通知

NotificationManager notificationManager = (NotificationManager) this

.getSystemService(NOTIFICATION_SERVICE);

notificationManager.cancel(0);

}

}

应用实例二:

我们在用手机的时候,如果来了短信,而我们没有点击查看的话,是不是在手机的最上边的状态栏里有一个短信的小图标提示啊?你是不是也想实现这种功能呢?今天的Notification就是解决这个问题的。

[java] view

plaincopy

package cn.com.chenzheng_java;

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.net.Uri;

import android.os.Bundle;

import android.provider.MediaStore.Audio;

import android.view.View;

import android.widget.Button;

/***

* @description 状态栏通知相关

* @author chenzheng_java

*

*/

public class NotificationActivity extends Activity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.notification);

Button button = (Button) findViewById(R.id.button);

button.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

addNotificaction();

}

});

}

/**

* 添加一个notification

*/

private void addNotificaction() {

NotificationManager manager = (NotificationManager) this

.getSystemService(Context.NOTIFICATION_SERVICE);

// 创建一个Notification

Notification notification = new Notification();

// 设置显示在手机最上边的状态栏的图标

notification.icon = R.drawable.excel;

// 当当前的notification被放到状态栏上的时候,提示内容

notification.tickerText = "注意了,我被扔到状态栏了";

/***

* notification.contentIntent:一个PendingIntent对象,当用户点击了状态栏上的图标时,该Intent会被触发

* notification.contentView:我们可以不在状态栏放图标而是放一个view

* notification.deleteIntent 当当前notification被移除时执行的intent

* notification.vibrate 当手机震动时,震动周期设置

*/

// 添加声音提示

notification.defaults=Notification.DEFAULT_SOUND;

// audioStreamType的值必须AudioManager中的值,代表着响铃的模式

notification.audioStreamType= android.media.AudioManager.ADJUST_LOWER;

//下边的两个方式可以添加音乐

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

//notification.sound = Uri.withAppendedPath(Audio.Media.INTERNAL_CONTENT_URI, "6");

Intent intent = new Intent(this, Notification2Activity.class);

PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);

// 点击状态栏的图标出现的提示信息设置

notification.setLatestEventInfo(this, "内容提示:", "我就是一个测试文件", pendingIntent);

manager.notify(1, notification);

}

}

点击按钮时候,状态栏会显示:

vcHLsMmjrNe0zKzAuLbgs/bAtNK7uPZleGNlbM28seqjrLWxztKwtNehzbyx6rK7t8WjrM35z8LNz7avtcTKsbryo6yz9sC0wcvV4rj20rPD5jwvcD4KPHA+CjxpbWcgc3JjPQ=="http://www.2cto.com/uploadfile/Collfiles/20140517/20140517091102107.gif" alt="\">

然后,当我们点击这个对话框之后,就会触发intent,跳转到Notification2Activity.java这个activity。

----------------------------------------------------------------------------------------

注意,NotificationManager里的notify(id,notification)中的id是用来唯一标识我们当前的这个notification的标识符,我们通过cancel方法删除通知时,传递的就是这个值。可能读者在看很多文档的时候,发现这个地方指定了一个莫名奇妙的值,例如R.drawable.icon,很多朋友就纳闷了,为什么这里要指定一个图片呢。这里笔者就介绍下,为什么呢?

答案其实很简单,我们都知道,我们这里对参数的唯一要求就是,这个id要和notify方法中的一致,并且是唯一;只要满足了这两项,其他的都无所谓。notify和cancel里一致我们作为开发者,太好控制了,但是唯一呢,我们还真不好说,于是这里就有些人动小脑筋了,很巧妙的用了我们系统中的图片资源或者其他资源的索引ID,我们都知道,这些值肯定都是唯一的!

------------------------------------------------------------------------------------------

下面是从网上找的一些资料:

如果要添加一个Notification,可以按照以下几个步骤

1:获取NotificationManager:

NotificationManager m_NotificationManager=(NotificationManager)this.getSystemService(NOTIFICATION_SERVICE);

2:定义一个Notification:

Notificationm_Notification=new Notification();

3:设置Notification的各种属性:

//设置通知在状态栏显示的图标

m_Notification.icon=R.drawable.icon;

//当我们点击通知时显示的内容

m_Notification.tickerText="Button1 通知内容.....";

通知时发出的默认声音

m_Notification.defaults=Notification.DEFAULT_SOUND;

//设置通知显示的参数

Intentm_Intent=new Intent(NotificationDemo.this,DesActivity.class);

PendingIntent m_PendingIntent=PendingIntent.getActivity(NotificationDemo.this, 0, m_Intent, 0);

m_Notification.setLatestEventInfo(NotificationDemo.this, "Button1", "Button1通知",m_PendingIntent );

//这个可以理解为开始执行这个通知

m_NotificationManager.notify(0,m_Notification);

4:既然可以增加同样我们也可以删除。当然是只是删除你自己增加的。

m_NotificationManager.cancel(0);

这里的0是一个ID号码,和notify第一个参数0一样。

这也就完成了,添加删除工作。

------------------------------------------------------------------------------------------------------

NoticificationManager很容易可以放在状态栏,也很容易实现从statusbar进入程序 中,

NoticificationManager中通过intent执行此程序的activity就可以了

NoticificationManager状态栏操作

NotificationManager(通知管理器):

NotificationManager负责通知用户事件的发生.

NotificationManager有三个公共方法:

1. cancel(int id) 取消以前显示的一个通知.假如是一个短暂的通知,试图将隐藏,假如是一个持久的通知,将从状态条中移走.

2. cancelAll() 取消以前显示的所有通知.

3. notify(int id,Notification notification) 把通知持久的发送到状态条上.

//初始化NotificationManager:

NotificationManager nm =

(NotificationManager)getSystemService(NOTIFICATION_SERVICE);

Notification代表着一个通知.

Notification的属性:

audioStreamType 当声音响起时,所用的音频流的类型

contentIntent 当通知条目被点击,就执行这个被设置的Intent.

contentView 当通知被显示在状态条上的时候,同时这个被设置的视图被显示.

defaults 指定哪个值要被设置成默认的.

deleteIntent 当用户点击"Clear All Notifications"按钮区删除所有的通知的时候,这个被设置的Intent被执行.

icon 状态条所用的图片.

iconLevel 假如状态条的图片有几个级别,就设置这里.

ledARGB LED灯的颜色.

ledOffMS LED关闭时的闪光时间(以毫秒计算)

ledOnMS LED开始时的闪光时间(以毫秒计算)

number 这个通知代表事件的号码

sound 通知的声音

tickerText 通知被显示在状态条时,所显示的信息

vibrate 振动模式.

when 通知的时间戳.

将Notification发送到状态条上:

Notification notification = new Notification();

Notification的设置过程……..

nm.notify(0, notification);//发送到状态条上

------------------------------------------------------------------------------------------------------------

Notification提供了丰富的手机提示方式:

a)在状态栏(Status Bar)显示的通知文本提示,如:

notification.tickerText = "hello";

b)发出提示音,如:

notification.defaults = Notification.DEFAULT_SOUND;

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

notification.sound = Uri.withAppendedPath(Audio.Media.INTERNAL_CONTENT_URI, "6");

c)手机振动,如:

notification.defaults = Notification.DEFAULT_VIBRATE;

long[] vibrate = {0,100,200,300};

notification.vibrate = vibrate;

d)LED灯闪烁,如:

notification.defaults = Notification.DEFAULT_LIGHTS;

notification.ledARGB = 0xff00ff00;

notification.ledOnMS = 300;

notification.ledOffMS = 1000;

notification.flags = Notification.FLAG_SHOW_LIGHTS;

4)发送通知:

private static final int ID_NOTIFICATION = 1;

mNotificationManager.notify(ID_NOTIFICATION, notification);

应用实例3---- 结合Broadcast 和Broadcast Receiver

private static final String ACTION_1="com.example.androidbasicdemo1.NEW_BROADCAST_1";

private static final String ACTION_2="com.example.androidbasicdemo1.NEW_BROADCAST_2";

@Override

public boolean onCreateOptionsMenu(Menu menu) {

menu.add(0,Menu.FIRST,0,"显示Notification");

menu.add(0,Menu.FIRST+1,0,"清楚Notification");

return super.onCreateOptionsMenu(menu);

}

@Override

public boolean onOptionsItemSelected(MenuItem item) {

int id = item.getItemId();

if (id == Menu.FIRST) {

actionClickMenuItem1();

return true;

}

if (id == Menu.FIRST+1) {

actionClickMenuItem2();

return true;

}

return super.onOptionsItemSelected(item);

}

private void actionClickMenuItem1() {

Intent intent1 = new Intent(ACTION_1);

sendBroadcast(intent1);

}

private void actionClickMenuItem2() {

Intent intent2 = new Intent(ACTION_2);

sendBroadcast(intent2);

}

Broadcast Receiver1

package com.example.broadcastreceiver;

import com.example.androidbasicdemo1.DBDemoActivity;

import android.R;

import android.app.Notification;

import android.app.NotificationManager;

import android.app.PendingIntent;

import android.content.BroadcastReceiver;

import android.content.Context;

import android.content.Intent;

/**

* 必须在AndroidManifest.xml中进行注册

* 自定义Broadcast Receiver继承BroadcastReceiver

* 重写onReceive()方法

*

* @author JayHe

*

*/

public class MyAndroidReceiver1 extends BroadcastReceiver {

private Context context;

public static int NOTIFICATION_ID=21321;

@Override

public void onReceive(Context context, Intent intent) {

this.context = context;

showNotification();

}

private void showNotification() {

NotificationManager notificationManager = (NotificationManager) context.getSystemService(android.content.Context.NOTIFICATION_SERVICE);

Notification notification = new Notification(R.drawable.ic_btn_speak_now, "来自MyReceiver1中", System.currentTimeMillis());

PendingIntent contentIntent = PendingIntent.getActivity(context, 0,

new Intent(context,DBDemoActivity.class), 0);

notification.setLatestEventInfo(context, "在MyReceiver1中", null, contentIntent);

notificationManager.notify(NOTIFICATION_ID, notification);

}

}

Broadcast Receiver2

package com.example.broadcastreceiver;

import android.app.NotificationManager;

import android.content.BroadcastReceiver;

import android.content.Context;

import android.content.Intent;

public class MyAndroidReceiver2 extends BroadcastReceiver {

Context context;

@Override

public void onReceive(Context context, Intent intent) {

this.context = context;

deleteNotification();

}

//deleteNotification方法将刚生成的Notification从状态栏删除。

/**

* 注意:每一个Notification都有一个唯一的id记性标识,而在程序中的这个Notification的id为MyAndroidReceiver1.NOTIFICATION_ID

*/

private void deleteNotification() {

NotificationManager notificationManager = (NotificationManager) context.getSystemService(android.content.Context.NOTIFICATION_SERVICE);

notificationManager.cancel(MyAndroidReceiver1.NOTIFICATION_ID);

}

}

赞助本站

人工智能实验室

相关热词: android开发

AiLab云推荐
展开

热门栏目HotCates

Copyright © 2010-2024 AiLab Team. 人工智能实验室 版权所有    关于我们 | 联系我们 | 广告服务 | 公司动态 | 免责声明 | 隐私条款 | 工作机会 | 展会港