Android之Notification讲解

来源:互联网 发布:mac怎么玩腾讯游戏 编辑:程序博客网 时间:2024/05/18 01:13

一、Notification简介:

  Notification,俗称通知,是一种具有全局效果的通知,它展示在屏幕的顶端,首先会表现为一个图标的形式,当用户向下滑动的时候,展示出通知具体的内容。程序一般通过NotificationManager服务来发送Notification。
  Android3.0增加了Notification.Builder类,该类可以轻松地创建Notification对象。

【注意】

  1. 兼容性问题:
      对于Notification而言,Android3.0是一个分水岭,如果不考虑向下兼容的问题,构建Notification使用Notification.Builder构建,如果考虑到向下兼容性的问题,一般推荐使用NotificationCompat.Builder构建(NotificationCompat类在v4包中:android.support.v4.app.NotificationCompat)。
      
  2. 发送通知:
      通知一般通过NotificationManager服务来发送一个Notification对象来完成,NotificationManager是一个重要的系统级服务,该对象位于应用程序的框架层中,应用程序可以通过它像系统发送全局的通知。这个时候需要创建一个Notification对象,用于承载通知的内容。但是一般在实际使用过程中,一般不会直接构建Notification对象,而是使用它的一个内部类NotificationCompat.Builder来实例化一个对象(Android3.0之下使用Notification.Builder),并设置通知的各种属性,最后通过NotificationCompat.Builder.build()方法得到一个Notification对象。当获得这个对象之后,可以使用NotificationManager.notify()方法发送通知。
      

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

  4. 通知的属性:
      虽然通知中提供了各种属性的设置,但是一个通知对象,有几个属性是必须要设置的,其他的属性均是可选的。
      • 小图标:使用setSamllIcon()方法设置。
      • 标题:使用setContentTitle()方法设置。
      • 文本内容:使用setContentText()方法设置。

二、Notification.Builder类中提供的方法:

  builder.setAutoCancel(); 设置点击通知后,状态栏自动删除通知。
  builder.setSmallIcon(R.drawable.alert); 设置通知小图标
  builder.setLargeIcon(R.drawable.alert2); 设置通知大图标
  builder.setContentTitle(“标题”); 设置通知标题
  builder.setContentText(“文本”); 设置通知内容
  builder.setContent(View view); 设置通知的自定义视图
  builder.setDefaults(Notification.DEFAULT_SOUND); 设置通知的音乐(系统默认)
  builder.setDefaults(Notification.DEFAULT_VIBRATE); 设置通知的振动(系统默认)
  builder.setDefaults(Notification.DEFAULT_LIGHTS); 设置通知的灯光(系统默认)
  builder.setSound(); 设置通知的音乐
  builder.setVibrate(); 设置通知的振动
  builder.setLights(); 设置通知的灯光
  builder.setTicker(); 设置通知在状态栏的提示文本。第一次提示消息的时候显示在通知栏上。
  builder.setContentIntent(); 设置点击通知后将要启动的程序组件对应的PendingIntent。

三、发送Notification的步骤:

  1、调用getSystemService(NOTIFICATION_SERVICE)方法获取系统的NotificationManager服务,它是一个重要的系统服务。应用程序可以通过NotificationManager 向系统发送全局通知;
  2、构造Notification.Builder对象;
  3、设置Notification.Builder对象的各种属性;
  4、创建Notification对象;
  5、通过NotificationManager 的notify()方法发送Notification。

  1. 创建Notification
    调用Notification.Builder对象的build()方法
  2. 更新Notification
    调用Notification的 setLatestEventInfo方法来更新内容,然后再调用NotificationManager的notify()方法即可
  3. 删除Notification
    通过NotificationManager的cancel(int)方法,来清除某个通知。其参数是Notification的唯一标识ID。
    当然也可以通过cancelAll() 来清除状态栏所有的通知。

四、案例演示:

代码如下:

package com.danny_jiang.day21_sendnotification;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.graphics.BitmapFactory;import android.os.Bundle;import android.support.v4.app.NotificationCompat;import android.view.View;import android.widget.RemoteViews;public class MainActivity extends Activity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);    }    public void click(View view) {        switch (view.getId()) {        case R.id.sendNormal:            sendNormal();            break;        case R.id.sendCustom:            sendCustom();            break;        default:            break;        }    }    /**     * 发送自定义通知(自定义视图)     */    private void sendCustom() {        // 创建通知的构建类        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);        // 设置当点击通知之后,自动删除        builder.setAutoCancel(true);        // 设置通知的小图标        builder.setSmallIcon(R.drawable.a0x);        // 初始化通知需要显示的RemoteViews对象        /*         * 第一个参数:包名  getPackageName获取         * 第二个参数:RemoteViews需要显示的布局文件ID         */        RemoteViews remoteView = new RemoteViews(getPackageName(),                 R.layout.nf_layout);        // 通过RemoteViews对象,可以操作内部显示的UI控件        remoteView.setTextViewText(R.id.textProgress, "已下载75%");        remoteView.setProgressBar(R.id.pb, 100, 75, false);        // 通过Builder.setContent方法设置通知的自定义视图        builder.setContent(remoteView);        // 设置点击通知后跳转的界面        Intent intent = new Intent(this, BAcitvity.class);        PendingIntent pendingIntent = PendingIntent.getActivity(this, 1,                intent, PendingIntent.FLAG_ONE_SHOT);        builder.setContentIntent(pendingIntent);        // 通过构建类获取Notification对象        Notification notification = builder.build();        // 获取通知管理器        NotificationManager manager = (NotificationManager) getSystemService(                Context.NOTIFICATION_SERVICE);        // 调用通知管理器的notify方法,发送通知        manager.notify(2, notification);    }    /**     * 发送普通通知     */    private void sendNormal() {        // 创建通知的构建类        NotificationCompat.Builder builder = new NotificationCompat.Builder(                this);        // 设置当点击通知之后,自动删除        builder.setAutoCancel(true);        // 设置通知的小图标        builder.setSmallIcon(R.drawable.a0x);        // 设置通知的大图标        builder.setLargeIcon(BitmapFactory.decodeResource(getResources(),                R.drawable.ic_launcher));        // 设置通知的标题        builder.setContentTitle("歌曲");        // 设置通知的正文        builder.setContentText("我的滑板鞋");        // 设置通知的闪烁文本信息        builder.setTicker("别人笑我太疯癫,我笑他人看不穿");        // 设置系统默认的振动、音乐、灯光        builder.setDefaults(Notification.DEFAULT_ALL);        /*         * 通过设置PendingIntent可以设置点击通知时,所触发的组件         * 通过PendingIntent.getActivity说明启动的是Activity组件         * 通过PendingIntent.getService说明启动的是Service组件         * 以上两个方法都必须传入意图Intent对象         */        Intent intent = new Intent(this, BAcitvity.class);        PendingIntent pendingIntent = PendingIntent.getActivity(this, 1,                intent, PendingIntent.FLAG_ONE_SHOT);        builder.setContentIntent(pendingIntent);        // 通过构建类获取Notification对象        Notification notification = builder.build();        // 获取通知管理器        NotificationManager manager = (NotificationManager) getSystemrvice(                Context.NOTIFICATION_SERVICE);        // 调用通知管理器的notify方法,发送通知        manager.notify(1, notification);    }}

nf_layout.xml布局文件如下:

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:id="@+id/remoteView"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:gravity="center"    android:orientation="vertical" >    <TextView        android:id="@+id/textProgress"        android:layout_width="wrap_content"        android:layout_height="72dp"        android:gravity="center"        android:text="已下载:" />    <TextView        android:id="@+id/show_msg2"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_marginLeft="12dp"        android:layout_marginTop="12dp"        android:layout_toRightOf="@id/textProgress"        android:text="正在下载..." />    <ProgressBar        android:id="@+id/pb"        style="?android:attr/progressBarStyleHorizontal"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_below="@id/show_msg2"        android:layout_marginLeft="12dp"        android:layout_toRightOf="@id/textProgress" /></RelativeLayout>

五、PendingIntent介绍

  1、PendingIntent字面意义:等待的,悬而未决的Intent;Intent一般是用作Activity、Sercvice、BroadcastReceiver之间传递数据,而Pendingintent一般用在 Notification上,可以理解为延迟执行的intent,PendingIntent是对Intent的一个包装;
  2、得到一个 PendingIntent 对象,使用PendingIntent 类的静态方法 getActivity(Context, int, Intent, int);
  3、PendingIntent是一种特殊的Intent。主要的区别在于Intent是立刻执行,而 PendingIntent 的执行不是立刻,而是当条件满足后才发送企图,而且PendingIntent 可以取消;
  4、PendingIntent执行的操作实质上是参数传进来的Intent的操作,使用 PendingIntent 的目的在于它所包含的Intent的操作的执行是需要满足某些条件的。
  5、主要的使用的地方和例子:通知Notification的发送,短消息SmsManager的发送和警报器AlarmManager的执行等。
  总而言之,PendingIntent就是一个可以在满足一定条件下执行的Intent,它相比于Intent的优势在于自己携带有Context对象,这样他就不必依赖于某个activity才可以存在。
  

Intent和PendingIntent的区别:
1. Intent是立即使用的,而PendingIntent可以等到事件发生后触发,PendingIntent可以cancel
2. PendingIntent自带Context,而Intent需要在某个Context内运行;
3. Intent在原task中运行,PendingIntent在新的task中运行。

六、getActivity(Context, int, Intent, int)方法中第四个参数介绍

  1.FLAG_CANCEL_CURRENT:如果当前系统中已经存在一个相同的PendingIntent对象,就先将已有的PendingIntent取消,然后重新生成一个PendingIntent对象。
  2.FLAG_NO_CREATE:如果当前系统中不存在相同的PendingIntent对象,系统将不会创建该PendingIntent对象而是直接返回null。
  3.FLAG_ONE_SHOT:该PendingIntent只作用一次。在该PendingIntent对象通过send()方法触发过后,PendingIntent将自动调用cancel()进行销毁,那么如果你再调用send()方法的话,系统将会返回一个SendIntentException。
  4.FLAG_UPDATE_CURRENT: 如果系统中有一个和你描述的PendingIntent对等的PendingInent,那么系统将使用该PendingIntent对象,但是会使用新的Intent来更新之前PendingIntent中的Intent对象数据,例如更新Intent中的Extras。
  
  更多有关Notification介绍,参考http://blog.csdn.net/loongggdroid/article/details/17616509
  http://blog.csdn.net/feng88724/article/details/6259071

0 0
原创粉丝点击