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

Android的通知(Notification)使用详解

2015-02-01 09:57 597 查看
这篇博客讲解一下在Android中使用Notification提示消息给用户,Notification是一种具有全局效果的通知,程序一般通过NotificationManager服务来发送Notification。在本篇博客中,将介绍Notification的常规使用,以及自定义方式的使用,对于每种不同的方式,都提供示例展示效果。

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移除指定通知示例:

NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.cancel(0);


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("twain@android.com");

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的使用,模仿上面图片的显示。

  实现代码:

btnBigViewNotification.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Bitmap btm = BitmapFactory.decodeResource(getResources(),
R.drawable.msg);
Intent intent = new Intent(MainActivity.this,
ResultActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(
MainActivity.this, 0, intent,
PendingIntent.FLAG_CANCEL_CURRENT);
Notification noti = new NotificationCompat.Builder(
MainActivity.this)
.setSmallIcon(R.drawable.msg)
.setLargeIcon(btm)
.setNumber(13)
.setContentIntent(pendingIntent)
.setStyle(
new NotificationCompat.InboxStyle()
.addLine(
"M.Twain (Google+) Haiku is more than a cert...")
.addLine("M.Twain Reminder")
.addLine("M.Twain Lunch?")
.addLine("M.Twain Revised Specs")
.addLine("M.Twain ")
.addLine(
"Google Play Celebrate 25 billion apps with Goo..")
.addLine(
"Stack Exchange StackOverflow weekly Newsl...")
.setBigContentTitle("6 new message")
.setSummaryText("mtwain@android.com"))
.build();
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(0, noti);
}
});


  展示效果:



进度条样式的通知

  对于一个标准通知,有时候显示的消息并不一定是静态的,还可以设定一个进度条用于显示事务完成的进度。

  Notification.Builder类中提供一个setProgress(int max,int progress,boolean indeterminate)方法用于设置进度条,max用于设定进度的最大数,progress用于设定当前的进度,indeterminate用于是否是一个确定进度只的进度条。通过indeterminate的设置,可以实现两种不同样式的进度条,一种是有进度的(false),一种是循环流动的(false)。下面分别用两个示例演示:

  有进度的进度条,实现代码:

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();
}
});


  显示效果:



  对于循环流动的进度条,下面是实现代码:

btnProNotification.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.setProgress(0, 0, true);//设置为true,表示流动
manager.notify(0, builder.build());
//5秒之后还停止流动
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
builder.setProgress(100, 100, false);//设置为true,表示刻度
manager.notify(0, builder.build());
}
}).start();
}
});


  效果展示:



自定义通知

  和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代码:

<RELATIVELAYOUT
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp" >
<IMAGEVIEW
android:id="@+id/imageNo"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_marginRight="10dp" />
<TEXTVIEW
android:id="@+id/titleNo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/imageNo" />
<TEXTVIEW
android:id="@+id/textNo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/titleNo"
android:layout_toRightOf="@id/imageNo" />


实现代码:

btnCustomNotification.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
RemoteViews contentViews = new RemoteViews(getPackageName(),
R.layout.custom_notification);
//通过控件的Id设置属性
contentViews
.setImageViewResource(R.id.imageNo, R.drawable.btm1);
contentViews.setTextViewText(R.id.titleNo, "自定义通知标题");
contentViews.setTextViewText(R.id.textNo, "自定义通知内容");
Intent intent = new Intent(MainActivity.this,
ResultActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(
MainActivity.this, 0, intent,
PendingIntent.FLAG_CANCEL_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
MainActivity.this).setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("My notification")
.setTicker("new message");
mBuilder.setAutoCancel(true);
mBuilder.setContentIntent(pendingIntent);
mBuilder.setContent(contentViews);
mBuilder.setAutoCancel(true);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(10, mBuilder.build());
}
});


  效果展示:



设定提示响应

  对于有些通知,需要调用一些设备的资源,使用户能更快的发现有新通知,一般可设定的响应有:铃声、闪光灯、震动。对于这三个属性,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中增加两个授权,分别授予访问振动器与闪光灯的权限:

<!-- 闪光灯权限 -->
<uses-permission android:name="android.permission.FLASHLIGHT"/>
<!-- 振动器权限 -->
<uses-permission android:name="android.permission.VIBRATE"/>


  因为只是一个属性的设定,并且大部分时候,使用系统设定即可,这里就不提供代码示例了。

总结

  通知算是Android中比较常用的一个功能,可以保持自己App的长存,在用户没有进入App的时候,也提供了与用户交互的可能。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: