您的位置:首页 > 移动开发 > Android开发

Android之Notification的多种用法

2016-04-06 15:02 591 查看
转载请标明出处:http://blog.csdn.net/xx326664162/article/details/51074832   文章出自:[薛瑄的博客](http://blog.csdn.net/xx326664162)
你也可以查看我的其他同类文章,也会让你有一定的收货!

我们在用手机的时候,如果来了短信,而我们没有点击查看的话,是不是在手机的最上边的状态栏里有一个短信的小图标提示啊?你是不是也想实现这种功能呢?Notification就是解决这个问题的。 
Android系统也是在不断升级的,有关Notification的用法也就有很多种,有的方法已经被android抛弃了,现在我实现了三种不同的方法,并适应不同的android版本。

先看效果图:







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

1、NotificationManager常用字段:

contentIntent   设置PendingIntent对象,点击时发送该Intent
defaults        添加默认效果(提示声音、闪光、震动等)
flags           设置flag位(是否可被清除等)
icon            设置图标
sound           设置声音
tickerText      显示在状态栏中的文字
when            发送此通知的时间戳


defaults变量可选值:

DEFAULT_ALL 使用所有默认值,比如声音,震动,闪屏等等
DEFAULT_LIGHTS 使用默认闪光提示
DEFAULT_SOUNDS 使用默认提示声音
DEFAULT_VIBRATE 使用默认手机震动
【说明】:加入手机震动,一定要在manifest.xml中加入权限:
<uses-permission android:name="android.permission.VIBRATE" />
以上的效果常量可以叠加

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

flag变量可选值:

FLAG_AUTO_CANCEL   该通知能被状态栏的清除按钮给清除掉
FLAG_NO_CLEAR      该通知不能被状态栏的清除按钮给清除掉
FLAG_ONGOING_EVENT 通知放置在正在运行
FLAG_INSISTENT     是否一直进行,比如音乐一直播放,知道用户响应

2、NotificationManager常用方法介绍:

public void cancelAll()     移除所有通知(只是针对当前Context下的Notification)
public  void cancel(int id) 移除标记为id的通知 (只是针对当前Context下的所有Notification)
public  void notify(String tag ,int id, Notification notification) 将通知加入状态栏,标签为tag,标记为id
public  void notify(int id, Notification notification) 将通知加入状态栏,标记为id


主要的代码如下:

package net.loonggg.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 MainActivity extends Activity {
private static final int NOTIFICATION_FLAG = 1;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

public void notificationMethod(View view) {
// 获取系统的通知服务,它是一个系统Service。
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

switch (view.getId()) {

// 第一种:默认通知(Android 6.0已经废弃setLatestEventInfo)
case R.id.btn1:
// 创建一个PendingIntent,和Intent类似,不同的是由于不是马上调用,需要在下拉状态条出发的activity,所以采用的是PendingIntent,即点击Notification跳转启动到哪个Activity
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);

// 下面需兼容Android 2.x版本是的处理方式
// Notification notify1 = new Notification(R.drawable.message,
// "TickerText:" + "您有新短消息,请注意查收!", System.currentTimeMillis());
Notification notify1 = new Notification();
notify1.icon = R.drawable.message;
notify1.tickerText = "TickerText:您有新短消息,请注意查收!";
notify1.when = System.currentTimeMillis();
notify1.setLatestEventInfo(this, "Notification Title",
"This is the notification message", pendingIntent);
notify1.number = 1;
notify1.flags |= Notification.FLAG_AUTO_CANCEL; // FLAG_AUTO_CANCEL表明当通知被用户点击时,通知将被清除。
// 通过通知管理器来发起通知。如果id不同(NOTIFICATION_FLAG),则显示不同的通知条。id相同的,则覆盖
manager.notify(NOTIFICATION_FLAG, notify1);
break;

// 默认通知 API11及之后可用
case R.id.btn2:
PendingIntent pendingIntent2 = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
// 通过Notification.Builder来创建通知,注意API Level
// API11之后才支持
Notification notify2 = new Notification.Builder(this)
.setSmallIcon(R.drawable.message) // 设置状态栏中的小图片,尺寸一般建议在24×24,这个图片同样也是在下拉状态栏中所显示,如果在那里需要更换更大的图片,可以使用setLargeIcon(Bitmap icon)
.setTicker("TickerText:" + "您有新短消息,请注意查收!")// 设置在status bar上显示的提示文字
.setContentTitle("Notification Title")// 设置在下拉status bar后Activity,本例子中的NotififyMessage的TextView中显示的标题
.setContentText("This is the notification message")// TextView中显示的详细内容
.setContentIntent(pendingIntent2) // 关联PendingIntent
.setNumber(1) // 在TextView的右方显示的数字,可放大图片看,在最右侧。这个number同时也起到一个序列号的左右,如果多个触发多个通知(同一ID),可以指定显示哪一个。
.getNotification(); // 注意在API level 16及之后使用build()来代替该函数,在API11中可以使用getNotificatin()
notify2.flags |= Notification.FLAG_AUTO_CANCEL;
manager.notify(NOTIFICATION_FLAG, notify2);
break;

// 默认通知 API16及之后可用
case R.id.btn3:
PendingIntent pendingIntent3 = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);
// 通过Notification.Builder来创建通知,注意API Level
// API16之后才支持
Notification notify3 = new Notification.Builder(this)
.setSmallIcon(R.drawable.message)
.setTicker("TickerText:" + "您有新短消息,请注意查收!")
.setContentTitle("Notification Title")
.setContentText("This is the notification message")
.setContentIntent(pendingIntent3)
.setNumber(1)
.build(); // 注意build()是在API level16及之后增加的,API11可以使用getNotificatin()来替代
notify3.flags |= Notification.FLAG_AUTO_CANCEL; // FLAG_AUTO_CANCEL表明当通知被用户点击时,通知将被清除。
manager.notify(NOTIFICATION_FLAG, notify3);// 通过通知管理器来发起通知。如果id不同(NOTIFICATION_FLAG),则显示不同的通知条。id相同的,则覆盖
break;

// 自定义通知
case R.id.btn4:
// Notification myNotify = new Notification(R.drawable.message,
// "自定义通知:您有新短信息了,请注意查收!", System.currentTimeMillis());
Notification myNotify = new Notification();
myNotify.icon = R.drawable.message;
myNotify.tickerText = "TickerText:您有新短消息,请注意查收!";
myNotify.when = System.currentTimeMillis();
myNotify.flags = Notification.FLAG_NO_CLEAR;// 不能够自动清除
RemoteViews rv = new RemoteViews(getPackageName(),
R.layout.my_notification);
rv.setTextViewText(R.id.text_content, "hello wrold!");
myNotify.contentView = rv;
Intent intent = new Intent(Intent.ACTION_MAIN);
PendingIntent contentIntent = PendingIntent.getActivity(this, 1, intent, 1);
myNotify.contentIntent = contentIntent;
manager.notify(NOTIFICATION_FLAG, myNotify);
break;

case R.id.btn5:
// 清除id为NOTIFICATION_FLAG的通知
manager.cancel(NOTIFICATION_FLAG);
// 清除所有的通知
// manager.cancelAll();
break;
default:
break;
}
}
}



API16 之后的使用.build()创建Notification对象 ,也可以使用下面的这种方式先创建Builder 对象,在使用.build()创建Notification对象
public void simpleNotice(View view) {
//此Builder为android.support.v4.app.NotificationCompat.Builder中的,下同。
Builder mBuilder = new Builder(this);
//系统收到通知时,通知栏上面显示的文字。
mBuilder.setTicker("天津,晴,2~15度,微风");
//显示在通知栏上的小图标
mBuilder.setSmallIcon(R.drawable.consult_answer);
//通知标题
mBuilder.setContentTitle("天气预报");
//通知内容
mBuilder.setContentText("天津,晴,2~15度,微风");

//设置大图标,即通知条上左侧的图片(如果只设置了小图标,则此处会显示小图标)
mBuilder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.share_sina));
//显示在小图标左侧的数字
mBuilder.setNumber(6);

//设置为不可清除模式
mBuilder.setOngoing(true);

//显示通知,id必须不重复,否则新的通知会覆盖旧的通知(利用这一特性,可以对通知进行更新)
nm.notify(1, mBuilder.build());
}

主布局文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >

<Button
android:id="@+id/btn1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="notificationMethod"
android:text="默认通知(已被抛弃,但是通用)" />

<Button
android:id="@+id/btn2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="notificationMethod"
android:text="默认通知(API11之后可用)" />

<Button
android:id="@+id/btn3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="notificationMethod"
android:text="默认通知(API16之后可用)" />

<Button
android:id="@+id/btn4"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="notificationMethod"
android:text="自定义通知" />

<Button
android:id="@+id/btn5"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="notificationMethod"
android:text="清除通知" />

</LinearLayout>


自定义通知的布局文件my_notification.xml,代码如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ffffff"
android:orientation="vertical" >

<TextView
android:id="@+id/text_content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp" />

</LinearLayout>

一些经验:

如果两个ID相同Notification对象的A和B,在下拉状态栏中,A是点击消失,B是点击不消失的,这样的话,点击A也不会消失。参考: 
http://blog.csdn.net/loongggdroid/article/details/17616509/ 
http://blog.csdn.net/books1958/article/details/41207435 
http://www.oschina.net/code/snippet_270292_14489 
http://www.cnblogs.com/error404/archive/2011/08/18/2144913.html
http://blog.csdn.net/feng88724/article/details/6259071
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: