您的位置:首页 > 其它

Notification的功能和用法

2016-01-04 16:10 387 查看
Notification的功能和用法
Notification是显示在手机状态栏的通知--手机状态栏位于设计屏幕的最上方,哪里一般显示手机当前的网络状态、电池状态、时间等。
Notification代表的是一种全局通知,程序一般通过NotificationManager服务来发送Notification。

创建一个通知Android为Notification增加了NotificationCompat.Builder类,通过该类允许开发者更轻松过的创建Notification对象为了创建自身通知, 可以使用 
NotificationCompat.Builder.build()
, 它返回一个包含您规范的Notification对象 。要发送通知,你可以通过调用系统的
NotificationManager.notify()方法。

通知必须包含的内容

通知对象必须包含如下内容:图标,
setSmallIcon()
标题,  
setContentTitle()
内容文本,  
setContentText()

可选的Notification内容和设置

其他内容和设置是可选的。了解更多内容请查看官方文档 
NotificationCompat.Builder
.

Notification动作与行为

虽然这也是可选的,但是你还是应该为你的notification至少添加一种行为:允许用户通过点击notification进入一个activity中进行更多的查看或者后续操作。一个notification可以提供多种动作,而且你也应该让用户点击一个notification之后能总是有相应的响应动作,通常是打开一个activity。你还可以在notification中添加能响应点击事件的button,比如延迟一下闹钟,或者立即回复一条短消息。在notification内部,一个动作本身是被定义在一个PendingIntent中,PendingIntent包含了一个用于启动你app中activity的intent。要将PendingIntent和一个手势联系起来,你需要调用合适的NotificationCompat.Builder方法。比如你想在点击notification文字的时候启动activity,你需要调用NotificationCompat.Builder的setContentIntent()来添加PendingIntent。启动一个activity是notification动作响应中最普遍的一类。

创建一个简单的Notification

下面的代码片段演示了一个打开activity的notification,注意这里获取PendingIntent是通过创建TaskStackBuilder对象:
NotificationCompat.Builder mBuilder =
        new NotificationCompat.Builder(this)
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle("My notification")
        .setContentText("Hello World!");
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(this, ResultActivity.class);
 
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(ResultActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
        stackBuilder.getPendingIntent(
            0,
            PendingIntent.FLAG_UPDATE_CURRENT
        );
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(mId, mBuilder.build());

通过上面的代码你就能为你的用户发出一个系统通知。

为Notification设置宽视图

要获得一个能展开的宽视图样式的notification首选创建一个普通的
NotificationCompat.Builder对象,然后调用Builder.setStyle()。记住这种notification只有4.1版本以上才支持。
下面的例子演示了在上面的普通notification的基础上添加宽视图风格的notification
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
    .setSmallIcon(R.drawable.notification_icon)
    .setContentTitle("Event tracker")
    .setContentText("Events received")
NotificationCompat.InboxStyle inboxStyle =
        new NotificationCompat.InboxStyle();
String[] events = new String[6];
// Sets a title for the Inbox in expanded layout
inboxStyle.setBigContentTitle("Event tracker details:");
...
// Moves events into the expanded layout
for (int i=0; i < events.length; i++) {
 
    inboxStyle.addLine(events[i]);
}
// Moves the expanded layout object into the notification object.
mBuilder.setStyle(inBoxStyle);
...
// Issue the notification here.

管理通知

当你多次发出类型相同的通知时,你应该避免做一个完全新的通知。相反,你应该考虑更新之前的通知,或者通过改变或增加它的一些值,或两者兼而有之。例如,Gmail的通知新邮件到达,通过增加未读邮件的数量和通过增加每封电子邮件摘要,以通知用户。这就是所谓的“堆积”的通知注:此Gmail的功能需要的“收件箱”展开布局,这是开始在安卓4.1的扩展通知功能可用的一部分。以下部分介绍了如何更新通知,以及如何删除它们。

删除通知

通知仍然可见,直到发生以下情况之一:用户可以单独或通过使用“全部清除”(如果通知可以被清除)驳回通知。当你创建通知时使用setAutoCancel()会在你转向另一个Activity后自动取消使用cancel()方法,可以取消正在执行的通知使用cancelAll()方法,它会删除所有以前发布的通知。 

进度显示

在操作的开始发出通知,动画将运行,直至修改通知,当操作完成后调用
setProgress(max, progress, false)
 方法然后更新所述通知到除去活动的指标。始终做到这一点; 否则,当在操作完成动画将运行偶数。还记得更改通知文本以表明操作完成。举例:
...
mNotifyManager =
        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mBuilder = new NotificationCompat.Builder(this);
mBuilder.setContentTitle("Picture Download")
    .setContentText("Download in progress")
    .setSmallIcon(R.drawable.ic_notification);
// Start a lengthy operation in a background thread
new Thread(
    new Runnable() {
        @Override
        public void run() {
            int incr;
            // Do the "lengthy" operation 20 times
            for (incr = 0; incr <= 100; incr+=5) {
                    // Sets the progress indicator to a max value, the
                    // current completion percentage, and "determinate"
                    // state
                    mBuilder.setProgress(100, incr, false);
                    // Displays the progress bar for the first time.
                    mNotifyManager.notify(0, mBuilder.build());
                        // Sleeps the thread, simulating an operation
                        // that takes time
                        try {
                            // Sleep for 5 seconds
                            Thread.sleep(5*1000);
                        } catch (InterruptedException e) {
                            Log.d(TAG, "sleep failure");
                        }
            }
            // When the loop is finished, updates the notification
            mBuilder.setContentText("Download complete")
            // Removes the progress bar
                    .setProgress(0,0,false);
            mNotifyManager.notify(ID, mBuilder.build());
        }
    }
// Starts the thread by calling the run() method in its Runnable
).start();
几点必要的说明
1:进行配置产生PendingIntent,与intent有区别 
      Intent :意图,即告诉系统我要干什么,然后系统根据这个Intent做对应的事。如startActivity相当于发送消息,而Intent是消息的内容。
        PendingIntent :包装Intent,Intent 是我们直接使用 startActivity , startService 或 sendBroadcast 启动某项工作的意图。而某些时候,我们并不能直接调用startActivity ,
        startServide 或 sendBroadcast ,而是当程序或系统达到某一条件才发送Intent。
        如这里的Notification,当用户点击Notification之后,由系统发出一条Activity 的 Intent 。
        因此如果我们不用某种方法来告诉系统的话,系统是不知道是使用 startActivity ,startService 还是 sendBroadcast 来启动Intent 的
        当然还有其他的“描述”),因此这里便需要PendingIntent。
2:如何使自己的Notification像Android QQ一样能出现在 “正在运行的”栏目下面其实很简单,只需设置Notification.flags = Notification.FLAG_ONGOING_EVENT;便可以了。
实例:显示后台下载信息的消息
程序清单:
private int  num=0;
 public void sentNotification(View view){
  Intent intent=new Intent(this,AlterDialogActivity.class);
     // PendingIntent.FLAG_UPDATE_CURRENT  表示如果该描述的PendingIntent已存在,则改变已存在的PendingIntent的Extra数据为新的PendingIntent的Extra数据。
  PendingIntent pendingIntent=PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
 
  Notification mNotify= new NotificationCompat.Builder(this)
//设置通知标题
 .setContentTitle("最新信息")
//设置通知内容
 .setContentText("元旦放假")
//设置通知在状态栏的提示文本
 .setTicker("有一个好消息")
//设置通知图标
 .setSmallIcon(R.mipmap.ic_qq_login_normal)
//设置点击通知后将要启动的程序组件对应的pendingIntent
 .setContentIntent(pendingIntent)
//设置通知LED灯、音乐、震动等
 .setDefaults(0)//设置默认声音
 .build();
  mNotificationManager.notify(++num,mNotify);
 }
 public void  downloadNotification(View view){
  final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
 .setSmallIcon(R.mipmap.ic_qq_login_normal)
 .setContentTitle("Event tracker")
 .setContentText("Events received");
  //启线程
  new Thread(new Runnable() {
@Override
public void run() {
 //根据下载任务,获得数据更新Nofitication
 for(int i=0;i<100;i+=5){
  try {
Thread.sleep(2000);
  } catch (InterruptedException e) {
e.printStackTrace();
  }
//进度显示
  mBuilder.setProgress(100,i,false);
//要发送通知,你可以通过调用系统的NotificationManager.notify()方法。
  mNotificationManager.notify(1, mBuilder.build());
 }
 mNotificationManager.cancel(1);
}
  }).start();
 }

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