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

android Notification

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

  因为Android的快速发展,而Android的版本也快速的升级导致了一些兼容性的问题。对于Notification而言,Android3.0是一个分水岭,在其之前构建Notification推荐使用NotificationCompate.Builder,它位于android.support.v4.app.NotificationCompat.Builder,是一个Android向下版本的兼容包,而在Android3.0之后,一般推荐使用Notification.Builder构建。本博客主要介绍的是Android4.x的开发,所以在这里使用Notification.Builder进行讲解演示。

  通知一般通过NotificationManager服务发送一个Notification对象来完成通知,NotificationManager是一个重要的系统级服务,该对象位于应用程序的框架层中,应用程序可以通过它向系统发送全局的通知。使用通知的时候,需要创建一个Notification对象用来承载通知的内容,但是一般不会直接通过Notification的构造方法来得到对象,而是使用它的内部类Notification.Builder来实例化一个Builder对象,并设置通知的各项属性,最后通过Notification.Builder.builder()方法得到一个Notification对象,当获得这个Notification对象之后,就可以使用NotificationManager.notify()方法发送通知。

  NotificationManager类是一个通知管理器类,这个对象是由系统维护的服务,是以单例模式的方式获得,所以一般并不直接实例化这个对象。在Activity中,可以使用Activity.getSystemService(String)方法获取NotificationManager对象,Activity.getSystemService(String)方法可以通过Android系统级服务的句柄,返回对应的对象。在这里需要返回NotificationManager,所以直接传递Context.NOTIFICATION_SERVICE即可。

  虽然通知中提供了各种属性的设置,但是一个通知对象,有几个属性是必须要设置的,其他的属性均是可选的,必须设置的属性如下:

小图标,使用setSamllIcon()方法设置。

标题,使用setContentTitle()方法设置。

文本内容,使用setContentText()方法设置。

PendingIntent

  对于一个通知而言,它显示的消息是有限的,一般仅用于提示一些概要信息。但是一般简短的消息,并不能表达需要告诉用户的全部内容,所以需要绑定一个意图,当用户点击通知的时候,调用一个意图展示出一个Activity用来显示详细的内容。而Notification中,并不使用常规的Intent去传递一个意图,而是使用PendingIntent。

  先来说说Intent和PendingIntent的区别,PendingIntent可以看做是对Intent的包装,通过名称可以看出PendingIntent用于处理即将发生的意图,而Intent用来用来处理马上发生的意图。而对于通知来说,它是一系统级的全局通知,并不确定这个意图被执行的时间。当在应用外部执行PendingIntent时,因为它保存了触发应用的Context,使得外部应用可以如在当前应用中一样,执行PendingIntent里的Intent,就算执行的时候响应通知的应用已经被销毁了,也可以通过存在PendingIntent里的Context照常执行它,并且还可以处理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+的版本。

  大视图notification只有在所有notification的最上面时才会显示大视图,其它情况下显示小视图。你也可以用手指将其扩展为大视图(前提是它是大视图)

  从官方文档了解到,一个标准视图显示的大小要保持在64dp高,宽度为屏幕标准。标准视图的通知主体内容有一下几个:



通知标题。

大图标。

通知内容。

通知消息。

小图标。

通知的时间,一般为系统时间,也可以使用setWhen()设置。

  下面通过一个示例,模仿上面效果的通知。

    

Bitmap btm = BitmapFactory.decodeResource(getResources(),R.drawable.logo);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MainActivity.this).setSmallIcon(R.drawable.logo)
.setContentTitle("5 new message")
.setContentText("twain@android.com");
mBuilder.setTicker("New message");//第一次提示消息的时候显示在通知栏上
mBuilder.setNumber(12);
mBuilder.setLargeIcon(btm);
mBuilder.setAutoCancel(true);//自己维护通知的消失

Intent resultIntent = new Intent(this,MainActivity.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的使用,模仿上面图片的显示。

  实现代码:

Intent resultIntent = new Intent(this,MainActivity.class);
//封装一个Intent
PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, 0, resultIntent,PendingIntent.FLAG_UPDATE_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的设置,可以实现两种不同样式的进度条,一种是有进度刻度的(true),一种是循环流动的(false)。下面分别用两个示例演示:

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

NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder 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);
mNotificationManager.notify(0, builder.build());
try {
Thread.sleep(300);
} catch (InterruptedException e) {
Log.i(TAG, "sleep failure");
}
}
builder.setContentText("Download complete")
.setProgress(0, 0, false);
mNotificationManager.notify(0, builder.build());
}
}).start();


  显示效果:



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

NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Picture Download")
.setContentText("Download in progress");
builder.setProgress(0, 0, true);//设置为true,表示流动
mNotificationManager.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,表示刻度
mNotificationManager.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代码:custom_notification.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
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" />

</RelativeLayout>


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


 效果展示:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: