我们在用手机的时候,如果来了短信,而我们没有点击查看的话,是不是在手机的最上边的状态栏里有一个短信的小图标提示啊?你是不是也想实现这种功能呢?今天的Notification就是解决这个问题的。
我们也知道Android系统也是在不断升级的,有关Notification的用法也就有很多种,有的方法已经被android抛弃了,现在我实现了三种不同的方法,并适应不同的android版本。现在我就把代码公布出来,我喜欢把解释写在代码中,在这里我就不多说了,先看效果图:
主要的代码如下:
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) {
// 在Android进行通知处理,首先需要重系统哪里获得通知管理器NotificationManager,它是一个系统Service。
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
switch (view.getId()) {
// 默认通知
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不同,则每click,在statu那里增加一个提示
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(); // 需要注意build()是在API level
// 16及之后增加的,在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);// 步骤4:通过通知管理器来发起通知。如果id不同,则每click,在status哪里增加一个提示
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;
}
}
}
再看主布局文件:
<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>
Notification
Notification,俗称通知,是一种具有全局效果的通知,它展示在屏幕的顶端,首先会表现为一个图标的形式,当用户向下滑动的时候,展示出通知具体的内容。
注意:因为一些Android版本的兼容性问题,对于Notification而言,Android3.0是一个分水岭,在其之前构建Notification推荐使用Notification.Builder构建,而在Android3.0之后,一般推荐使用NotificationCompat.Builder构建。本文的所有代码环境均在4.3中完成,如果使用4.1一下的设备测试,请注意兼容性问题。
通知一般通过NotificationManager服务来发送一个Notification对象来完成,NotificationManager是一个重要的系统级服务,该对象位于应用程序的框架层中,应用程序可以通过它像系统发送全局的通知。这个时候需要创建一个Notification对象,用于承载通知的内容。但是一般在实际使用过程中,一般不会直接构建Notification对象,而是使用它的一个内部类NotificationCompat.Builder来实例化一个对象(Android3.0之下使用Notification.Builder),并设置通知的各种属性,最后通过NotificationCompat.Builder.build()方法得到一个Notification对象。当获得这个对象之后,可以使用NotificationManager.notify()方法发送通知。
NotificationManager类是一个通知管理器类,这个对象是由系统维护的服务,是以单例模式获得,所以一般并不直接实例化这个对象。在Activity中,可以使用Activity.getSystemService(String)方法获取NotificationManager对象,Activity.getSystemService(String)方法可以通过Android系统级服务的句柄,返回对应的对象。在这里需要返回NotificationManager,所以直接传递Context.NOTIFICATION_SERVICE即可。
虽然通知中提供了各种属性的设置,但是一个通知对象,有几个属性是必须要设置的,其他的属性均是可选的,必须设置的属性如下:
?小图标,使用setSamllIcon()方法设置。
?标题,使用setContentTitle()方法设置。
?文本内容,使用setContentText()方法设置。
更新与移除通知
在使用NotificationManager.notify()发送通知的时候,需要传递一个标识符,用于唯一标识这个通知。对于有些场景,并不是无限的添加新的通知,有时候需要更新原有通知的信息,这个时候可以重写构建Notification,而使用与之前通知相同标识符来发送通知,这个时候旧的通知就被被新的通知所取代,起到更新通知的效果。
对于一个通知,当展示在状态栏之后,但是使用过后,如何取消呢?Android为我们提供两种方式移除通知,一种是Notification自己维护,使用setAutoCancel()方法设置是否维护,传递一个boolean类型的数据。另外一种方式使用NotificationManager通知管理器对象来维护,它通过notify()发送通知的时候,指定的通知标识Id来操作通知,可以使用cancel(int)来移除一个指定的通知,也可以使用cancelAll()移除所有的通知。
使用NotificationManager移除指定通知示例:
1 2 |
|
PendingIntent
对于一个通知而言,它显示的消息是有限的,一般仅用于提示一些概要信息。但是一般简短的消息,并不能表达需要告诉用户的全部内容,所以需要绑定一个意图,当用户点击通知的时候,调用一个意图展示出一个Activity用来显示详细的内容。而Notification中,并不使用常规的Intent去传递一个意图,而是使用PendingIntent。
先来聊聊Intent和PendingIntent的区别,PendingIntent可以看做是对Intent的包装,通过名称可以看出PendingIntent用于处理即将发生的意图,而Intent用来处理马上发生的意图。而对于通知来说,它是一个系统级的全局的通知,并不确定这个意图被执行的时间。当在应用外部执行PendingIntent时,因为它保存了触发App的Context,使得外部App可以如果当前App一样执行PendingIntent里的Intent,就算执行时触发通知的App已经不存在了,也能通过存在PendingIntent里的Context照常执行Intent,并且还可以处理Intent所带来的额外的信息。
PendingIntent提供了多个静态的getXxx()方法,用于获得适用于不同场景的PendingIntent对象。一般需要传递的几个参数都很常规,只介绍一个flag参数,用于标识PendingIntent的构造选择:
?FLAG_CANCEL_CURRENT:如果构建的PendingIntent已经存在,则取消前一个,重新构建一个。
?FLAG_NO_CREATE:如果前一个PendingIntent已经不存在了,将不再构建它。
?FLAG_ONE_SHOT:表明这里构建的PendingIntent只能使用一次。
?FLAG_UPDATE_CURRENT:如果构建的PendingIntent已经存在,则替换它,常用。
Notification视觉风格
Notification有两种视觉风格,一种是标准视图(Normal view)、一种是大视图(Big view)。标准视图在Android中各版本是通用的,但是对于大视图而言,仅支持Android4.1+的版本。
从官方文档了解到,一个标准视图显示的大小要保持在64dp高,宽度为屏幕标准。标准视图的通知主体内容有一下几个:
- 通知标题。大图标。通知内容。通知消息。小图标。通知的时间,一般为系统时间,也可以使用setWhen()设置。
下面通过一个示例,模仿上面效果的通知。
btnNotification.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Bitmap btm = BitmapFactory.decodeResource(getResources(),
R.drawable.msg);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
MainActivity.this).setSmallIcon(R.drawable.msg)
.setContentTitle("5 new message")
.setContentText("[email protected]");
mBuilder.setTicker("New message");//第一次提示消息的时候显示在通知栏上
mBuilder.setNumber(12);
mBuilder.setLargeIcon(btm);
mBuilder.setAutoCancel(true);//自己维护通知的消失
//构建一个Intent
Intent resultIntent = new Intent(MainActivity.this,
ResultActivity.class);
//封装一个Intent
PendingIntent resultPendingIntent = PendingIntent.getActivity(
MainActivity.this, 0, resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
// 设置通知主题的意图
mBuilder.setContentIntent(resultPendingIntent);
//获取通知管理器对象
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(0, mBuilder.build());
}
}); 复制代码
显示效果:
而对于大视图(Big View)而言,它的细节区域只能显示256dp高度的内容,并且只对Android4.1+之后的设备才支持,它比标准视图不一样的地方,均需要使用setStyle()方法设定,它大致的效果如下:
setStyle()传递一个NotificationCompat.Style对象,它是一个抽象类,Android为我们提供了三个实现类,用于显示不同的场景。分别是:
NotificationCompat.BigPictureStyle, 在细节部分显示一个256dp高度的位图。NotificationCompat.BigTextStyle,在细节部分显示一个大的文本块。NotificationCompat.InboxStyle,在细节部分显示一段行文本。
如果仅仅显示一个图片,使用BigPictureStyle是最方便的;如果需要显示一个富文本信息,则可以使用BigTextStyle;如果仅仅用于显示一个文本的信息,那么使用InboxStyle即可。后面会以一个示例来展示InboxStyle的使用,模仿上面图片的显示。
实现代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
|
展示效果:
进度条样式的通知<喎?"http://www.2cto.com/kf/ware/vc/" target="_blank" class="keylink">vc3Ryb25nPjxicj4KPGJyPgqhoaGhttTT2tK7uPax6te8zajWqqOs09DKsbryz9TKvrXEz/vPorKisrvSu7aoyse+ssystcSjrLu5v8nS1MnotqjSu7j2vfi2yMz108PT2s/Uyr7Kws7xzeqzybXEvfi2yKGjPGJyPgo8YnI+CqGhoaFOb3RpZmljYXRpb24uQnVpbGRlcsDg1tDM4bmp0ru49nNldFByb2dyZXNzKGludCBtYXgsaW50IHByb2dyZXNzLGJvb2xlYW4gaW5kZXRlcm1pbmF0ZSm3vbeo08PT2sno1sO9+LbIzPWjrG1heNPD09rJ6Laovfi2yLXE1+6088r9o6xwcm9ncmVzc9PD09rJ6LaotbHHsLXEvfi2yKOsaW5kZXRlcm1pbmF0ZdPD09rKx7fxysfSu7j2yLe2qL34tsjWu7XEvfi2yMz1oaPNqLn9aW5kZXRlcm1pbmF0ZbXEyejWw6Osv8nS1Mq1z9bBvdbWsrvNrNH5yr21xL34tsjM9aOs0rvW1srH09C9+LbItcSjqGZhbHNlo6ks0rvW1srH0a27t8H3tq+1xKOoZmFsc2WjqaGjz8LD5rfWsfDTw8G9uPbKvsD90d3KvqO6PGJyPgo8YnI+CqGhoaHT0L34tsi1xL34tsjM9aOsyrXP1rT6wuujuiA8YnI+Cjxicj4KPHByZSBjbGFzcz0="brush:java;">
btnProgreNotification.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); builder = new NotificationCompat.Builder(MainActivity.this) .setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Picture Download") .setContentText("Download in progress"); builder.setAutoCancel(true); //通过一个子线程,动态增加进度条刻度 new Thread(new Runnable() { @Override public void run() { int incr; for (incr = 0; incr <= 100; incr += 5) { builder.setProgress(100,
incr, false); manager.notify(0, builder.build()); try { Thread.sleep(300); } catch (InterruptedException e) { Log.i(TAG, "sleep failure"); } } builder.setContentText("Download complete") .setProgress(0, 0, false); manager.notify(0, builder.build()); } }).start();
} });
显示效果:
对于循环流动的进度条,下面是实现代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
|
效果展示:
自定义通知
和Toast一样,通知也可以使用自定义的XML来自定义样式,但是对于通知而言,因为它的全局性,并不能简单的通过inflate膨胀出一个View,因为可能触发通知的时候,响应的App已经关闭,无法获取当指定的XML布局文件。所以需要使用单独的一个RemoteViews类来操作。
RemoteViews,描述了一个视图层次的结构,可以显示在另一个进程。层次结构也是从布局文件中“膨胀”出一个视图,这个类,提供了一些基本的操作求改其膨胀的内容。
RemoteViews提供了多个构造函数,一般使用RemoteViews(String packageName,int layoutId)。第一个参数为包的名称,第二个为layout资源的Id。当获取到RemoteViews对象之后,可以使用它的一系列setXxx()方法通过控件的Id设置控件的属性。最后使用NotificationCompat.Builder.setContent(RemoteViews)方法设置它到一个Notification中。
下面通过一个示例展示它:
自定义的布局XML代码:
1 2 3 4 |
|
实现代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
|
效果展示:
设定提示响应
对于有些通知,需要调用一些设备的资源,使用户能更快的发现有新通知,一般可设定的响应有:铃声、闪光灯、震动。对于这三个属性,NotificationCompat.Builder提供了三个方法设定:
setSound(Uri sound):设定一个铃声,用于在通知的时候响应。传递一个Uri的参数,格式为“file:///mnt/sdcard/Xxx.mp3”。setLights(
int argb, int onMs, int offMs
):设定前置LED灯的闪烁速率,持续毫秒数,停顿毫秒数。setVibrate(long[] pattern):设定震动的模式,以一个long数组保存毫秒级间隔的震动。
大多数时候,我们并不需要设定一个特定的响应效果,只需要遵照用户设备上系统通知的效果即可,那么可以使用setDefaults(int)方法设定默认响应参数,在Notification中,对它的参数使用常量定义了,我们只需使用即可:
DEFAULT_ALL:铃声、闪光、震动均系统默认。DEFAULT_SOUND:系统默认铃声。DEFAULT_VIBRATE:系统默认震动。DEFAULT_LIGHTS:系统默认闪光。
而在Android中,如果需要访问硬件设备的话,是需要对其进行授权的,所以需要在清单文件AndroidManifest.xml中增加两个授权,分别授予访问振动器与闪光灯的权限:
1 2 3 4 |
|
因为只是一个属性的设定,并且大部分时候,使用系统设定即可,这里就不提供代码示例了。
总结
通知算是Android中比较常用的一个功能,可以保持自己App的长存,在用户没有进入App的时候,也提供了与用户交互的可能。