全面解析Notification

Android 之 Notification (状态栏通知)详解 本节带来的是Android中用于在状态栏显示通知信息的控件:Notification,相信大部分 学Android都对他都很熟悉,而网上很多关于Notification的使用教程都是基于2.x的,而 现在普遍的Android设备基本都在4.x以上,甚至是5.0以上的都有;.setSound(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.biaobiao)) //设置自定义的提示音。//取消Notification。 阅读详情

Notification在Android中使用的频率可以说是非常高的,本篇博客,我将围绕着Notification的各方面进行解析,使大家对Notification有更好的认识。

Notification的使用步骤

1.获取NotificationManager

NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);  

2.创建NotificationCompat.Builder

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);  

3.对Builder设置一些Notification相关属性:

mBuilder.setContentTitle("标题")//设置通知栏标题  
    .setContentText("内容") //设置通知栏显示内容 
    .setContentIntent(getDefalutIntent(Notification.FLAG_AUTO_CANCEL)) //设置通知栏点击意图  
//  .setNumber(number) //设置通知集合的数量  
    .setTicker("通知到来") //通知首次出现在通知栏,带上升动画效果的  
    .setWhen(System.currentTimeMillis())//通知产生的时间,会在通知信息里显示,一般是系统获取到的时间  
    .setPriority(Notification.PRIORITY_DEFAULT) //设置该通知优先级  
//  .setAutoCancel(true)//设置这个标志当用户单击面板就可以让通知将自动取消    
    .setOngoing(false)//ture,设置他为一个正在进行的通知。他们通常是用来表示一个后台任务,用户积极参与(如播放音乐)或以某种方式正在等待,因此占用设备(如一个文件下载,同步操作,主动网络连接)  
    .setDefaults(Notification.DEFAULT_VIBRATE)//向通知添加声音、闪灯和振动效果的最简单、最一致的方式是使用当前的用户默认设置,使用defaults属性,可以组合  
    //Notification.DEFAULT_ALL  Notification.DEFAULT_SOUND 添加声音 // requires VIBRATE permission  
    .setSmallIcon(R.drawable.ic_launcher);//设置通知小ICON  

4.使用Builder创建通知

Notification notification = mBuilder.build();

5.使用NotificationManager将通知推送出去

int id = 199;
LogUtils.d(TAG, "创建通知");
mNotificationManager.notify(id, notification);

Notification重要方法解析

Notification 的基本操作主要有创建、更新、取消这三种。一个 Notification 的必要属性有三项,如果不设置则在运行时会抛出异常:

  1. 小图标,通过 setSmallIcon() 方法设置
  2. 标题,通过 setContentTitle() 方法设置
  3. 内容,通过 setContentText() 方法设置

除了以上三项,其它均为可选项。虽然如此,但还是应该给 Notification 设置一个 Action ,这样就可以直接跳转到 App 的某个 Activity 、启动一个 Service 或者发送一个 Broadcast。否则,Notification 仅仅只能起到通知的效果,而不能与用户交互。
当系统接收到通知时,可以通过震动、响铃、呼吸灯等多种方式进行提醒。

1) setSmallIcon() 与 setLargeIcon()
在 NotificationCompat.Builder 中有设置通知的大小图标的两个方法。这两个方法有什么区别呢?当 setSmallIcon() 与 setLargeIcon() 同时存在时, smallIcon 显示在largeIcon的右下角;当只设置 setSmallIcon() 时, smallIcon 显示在左侧。看下图你就明白了。对于部分 ROM ,可能修改过源码,如 MIUI 上通知的大图标和小图标是没有区别的。
这里写图片描述
Google 官方是这么解释 setSmallIcon() 这个方法的:

Set the small icon resource, which will be used to represent the notification in the status bar. The platform template for the expanded view will draw this icon in the left, unless a large icon has also been specified, in which case the small icon will be moved to the right-hand side.

2) 设置提醒标志符Flags
方法解释:提醒标志符,向通知添加声音、闪灯和振动效果等设置达到通知提醒效果,可以组合多个属性
a) 创建通知栏之后通过给他添加.flags属性赋值。

1.	Notification notification = mBuilder.build();  
2.	notification.flags = Notification.FLAG_AUTO_CANCEL; 

b)	通过setContentIntent(PendingIntent intent)方法中的意图设置对应的flags
1.	public PendingIntent getDefalutIntent(int flags){  
2.	    PendingIntent pendingIntent= PendingIntent.getActivity(this, 1, new Intent(), flags);  
3.	    return pendingIntent;  
4.	}  

各标志符介绍

Notification.FLAG_SHOW_LIGHTS              //三色灯提醒,在使用三色灯提醒时候必须加该标志符
Notification.FLAG_ONGOING_EVENT          //发起正在运行事件(活动中)
Notification.FLAG_INSISTENT   //让声音、振动无限循环,直到用户响应 (取消或者打开)
Notification.FLAG_ONLY_ALERT_ONCE  //发起Notification后,铃声和震动均只执行一次
Notification.FLAG_AUTO_CANCEL      //用户单击通知后自动消失
Notification.FLAG_NO_CLEAR          //只有全部清除时,Notification才会清除 ,不清楚该通知(QQ的通知无法清除,就是用的这个)
Notification.FLAG_FOREGROUND_SERVICE    //表示正在运行的服务

3) .setDefaults(int defaults) (NotificationCompat.Builder中的方法,用于设置通知到来时,通过什么方式进行提示)

方法解释:向通知添加声音、闪灯和振动效果的最简单、使用默认(defaults)属性,可以组合多个属性(和方法1中提示效果一样的)
对应属性:
Notification.DEFAULT_VIBRATE //添加默认震动提醒 需要 VIBRATE permission

Notification.DEFAULT_SOUND // 添加默认声音提醒
Notification.DEFAULT_LIGHTS// 添加默认三色灯提醒
Notification.DEFAULT_ALL// 添加默认以上3种全部提醒

/**
* 显示带有默认铃声、震动、呼吸灯效果的通知
* 如需实现自定义效果,请参考后面三个例子
*/
private void showNotifyWithMixed() {
   NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
           .setSmallIcon(R.mipmap.ic_launcher)
           .setContentTitle("我是有铃声+震动+呼吸灯效果的通知")
           .setContentText("库里就是叼~")
           //等价于setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE);
           .setDefaults(Notification.DEFAULT_ALL);
   mManager.notify(5, builder.build());
}

4) setVibrate(long[] pattern)
方法解释:设置震动的时间

.setVibrate(new long[] {0,300,500,700});  

实现效果:延迟0ms,然后振动300ms,在延迟500ms,接着在振动700ms。
还有另外一种写法:

mBuilder.build().vibrate = new long[] {0,300,500,700};  

如果希望设置默认振动方式,设置了方法(2)中默认为DEFAULT_VIBRATE 即可。
例子:

/**
* 展示有震动效果的通知,需要在AndroidManifest.xml中申请震动权限
* <uses-permission android:name="android.permission.VIBRATE" />
* 补充:测试震动的时候,手机的模式一定要调成铃声+震动模式,否则你是感受不到震动的
*/
private void showNotifyWithVibrate() {
   //震动也有两种设置方法,与设置铃声一样,在此不再赘述
   long[] vibrate = new long[]{0, 500, 1000, 1500};
   NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
           .setSmallIcon(R.mipmap.ic_launcher)
           .setContentTitle("我是伴有震动效果的通知")
           .setContentText("颤抖吧,凡人~")
           //使用系统默认的震动参数,会与自定义的冲突
           //.setDefaults(Notification.DEFAULT_VIBRATE)
           //自定义震动效果
           .setVibrate(vibrate);
   //另一种设置震动的方法
   //Notification notify = builder.build();
   //调用系统默认震动
   //notify.defaults = Notification.DEFAULT_VIBRATE;
   //调用自己设置的震动
   //notify.vibrate = vibrate;
   //mManager.notify(3,notify);
   mManager.notify(3, builder.build());
}

4)方法:.setLights(intledARGB ,intledOnMS ,intledOffMS )
方法解释:android支持三色灯提醒,这个方法就是设置不同场景下的不同颜色的灯。
描述:其中ledARGB 表示灯光颜色、 ledOnMS 亮持续时间、ledOffMS 暗的时间。
注意:
1)只有在设置了标志符Flags为Notification.FLAG_SHOW_LIGHTS的时候,才支持三色灯提醒。
2)这边的颜色跟设备有关,不是所有的颜色都可以,要看具体设备。

Notification notify = mBuilder.build();  
notify .setLights(0xff00eeff, 500, 200)  

同理,以下方法也可以设置同样效果:

Notification notify = mBuilder.build();  
notify.flags = Notification.FLAG_SHOW_LIGHTS;  
notify.ledARGB = 0xff00eeff;  
notify.ledOnMS = 500;  
notify.ledOffMS = 400; 

如果希望使用默认的三色灯提醒,设置了方法(2)中默认为DEFAULT_LIGHTS即可。
例子:

/**
* 显示带有呼吸灯效果的通知,但是不知道为什么,自己这里测试没成功
*/
private void showNotifyWithLights() {
   final NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
           .setSmallIcon(R.mipmap.ic_launcher)
           .setContentTitle("我是带有呼吸灯效果的通知")
           .setContentText("一闪一闪亮晶晶~")
           //ledARGB 表示灯光颜色、 ledOnMS 亮持续时间、ledOffMS 暗的时间
           .setLights(0xFF0000, 3000, 3000);
   Notification notify = builder.build();
   //只有在设置了标志符Flags为Notification.FLAG_SHOW_LIGHTS的时候,才支持呼吸灯提醒。
   notify.flags = Notification.FLAG_SHOW_LIGHTS;
   //设置lights参数的另一种方式
   //notify.ledARGB = 0xFF0000;
   //notify.ledOnMS = 500;
   //notify.ledOffMS = 5000;
   //使用handler延迟发送通知,因为连接usb时,呼吸灯一直会亮着
   Handler handler = new Handler();
   handler.postDelayed(new Runnable() {
       @Override
       public void run() {
           mManager.notify(4, builder.build());
       }
   }, 10000);
}


5)方法:.setSound(Uri sound)

方法解释:设置默认或则自定义的铃声,来提醒。

//获取默认铃声  
.setDefaults(Notification.DEFAULT_SOUND)  
//获取自定义铃声  
.setSound(Uri.parse("file:///sdcard/dance.mp3"))  
//获取Android多媒体库内的铃声  
.setSound(Uri.withAppendedPath(Audio.Media.INTERNAL_CONTENT_URI, "5"))  

同理相同效果的另一种设置方法这边就不讲, 和上面的都是一样的。
例子:

/**
* 展示有自定义铃声效果的通知
* 补充:使用系统自带的铃声效果:Uri.withAppendedPath(Audio.Media.INTERNAL_CONTENT_URI, "6");
*/
private void showNotifyWithRing() {
   NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
           .setSmallIcon(R.mipmap.ic_launcher)
           .setContentTitle("我是伴有铃声效果的通知")
           .setContentText("美妙么?安静听~")
           //调用系统默认响铃,设置此属性后setSound()会无效
           //.setDefaults(Notification.DEFAULT_SOUND)
           //调用系统多媒体裤内的铃声
           //.setSound(Uri.withAppendedPath(MediaStore.Audio.Media.INTERNAL_CONTENT_URI,"2"));
           //调用自己提供的铃声,位于 /res/values/raw 目录下
           .setSound(Uri.parse("android.resource://com.littlejie.notification/" + R.raw.sound));
   //另一种设置铃声的方法
   //Notification notify = builder.build();
   //调用系统默认铃声
   //notify.defaults = Notification.DEFAULT_SOUND;
   //调用自己提供的铃声
   //notify.sound = Uri.parse("android.resource://com.littlejie.notification/"+R.raw.sound);
   //调用系统自带的铃声
   //notify.sound = Uri.withAppendedPath(MediaStore.Audio.Media.INTERNAL_CONTENT_URI,"2");
   //mManager.notify(2,notify);
   mManager.notify(2, builder.build());
}


6)方法:.setPriority(int pri)
方法解释:设置优先级(实际项目中并无大用,设置最高级也不会使得你的通知栏出现在第一位)
这里写图片描述
对应属性:
Notification.PRIORITY_DEFAULT(优先级为0)
Notification.PRIORITY_HIGH
Notification.PRIORITY_LOW
Notification.PRIORITY_MAX(优先级为2)
Notification.PRIORITY_MIN(优先级为-2)

Notification.PRIORITY_MAX是优先级最高,Notification.PRIORITY_MIN优先级最低

7)方法:setOngoing(boolean ongoing)
方法解释:设置为ture,表示它为一个正在进行的通知。他们通常是用来表示一个后台任务,用户积极参与(如播放音乐)或以某种方式正在等待,因此占用设备(如一个文件下载,同步操作,主动网络连接)

PS:我们看到360手机卫士的通知栏一直固定在手机中,就是通过设置这个标记,使用该标记后你的通知栏无法被用户手动进行删除,只能通过代码进行删除,慎用

8)setProgress(int max, int progress,boolean indeterminate)
属性:max:进度条最大数值 、progress:当前进度、indeterminate:表示进度是否不确定,true为不确定,false为确定
功能:设置带进度条的通知,可以在下载中使用

注意:此方法在4.0及以后版本才有用,如果为早期版本:需要自定义通知布局,其中包含ProgressBar视图
使用:如果为确定的进度条:调用setProgress(max, progress, false)来设置通知,在更新进度的时候在此发起通知更新progress,并且在下载完成后要移除进度条,通过调用setProgress(0, 0, false)既可。
如果为不确定(持续活动)的进度条,这是在处理进度无法准确获知时显示活动正在持续,所以调用setProgress(0, 0, true) ,操作结束时,调用setProgress(0, 0, false)并更新通知以移除指示条

9)如何更新 Notification
更新通知很简单,只需要再次发送相同 ID 的通知即可,如果之前的通知还未被取消,则会直接更新该通知相关的属性;如果之前的通知已经被取消,则会重新创建一个新通知。
更新通知跟发送通知使用相同的方式。

private void refreshNotification() {
   //获取NotificationManager实例
   NotificationManager notifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
   //实例化NotificationCompat.Builde并设置相关属性
   NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
           //设置小图标
           .setSmallIcon(R.mipmap.icon_fab_repair)
           //设置通知标题
           .setContentTitle("最简单的Notification")
           //设置通知内容
           .setContentText("只有小图标、标题、内容")
           //设置通知时间,默认为系统发出通知的时间,通常不用设置
           //.setWhen(System.currentTimeMillis());
   //通过builder.build()方法生成Notification对象,并发送通知,id=1
   notifyManager.notify(1, builder.build());
}

10)如何取消 Notification?
取消通知有如下 5 种方式:

  1. 点击通知栏的清除按钮,会清除所有可清除的通知
  2. 设置了 setAutoCancel() 或 FLAG_AUTO_CANCEL 的通知,点击该通知时会清除它
  3. 通过 NotificationManager 调用 cancel(int id) 方法清除指定 ID 的通知
  4. 通过 NotificationManager 调用 cancel(String tag, int id) 方法清除指定 TAG 和 ID 的通知
  5. 通过 NotificationManager 调用 cancelAll() 方法清除所有该应用之前发送的通知
    如果你是通过 NotificationManager.notify(String tag, int id, Notification notify) 方法创建的通知,那么只能通过 NotificationManager.cancel(String tag, int id) 方法才能清除对应的通知,调用NotificationManager.cancel(int id) 无效。

例子:

public class DemoActivity extends Activity implements View.OnClickListener {

    //Notification.FLAG_FOREGROUND_SERVICE    //表示正在运行的服务
    public static final String NOTIFICATION_TAG = "test";
    public static final int DEFAULT_NOTIFICATION_ID = 1;

    private NotificationManager mNotificationManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_simple_notification);

        findViewById(R.id.btn_remove_all_notification).setOnClickListener(this);
        findViewById(R.id.btn_send_notification).setOnClickListener(this);
        findViewById(R.id.btn_remove_notification).setOnClickListener(this);
        findViewById(R.id.btn_send_notification_with_tag).setOnClickListener(this);
        findViewById(R.id.btn_remove_notification_with_tag).setOnClickListener(this);
        findViewById(R.id.btn_send_ten_notification).setOnClickListener(this);
        findViewById(R.id.btn_send_flag_no_clear_notification).setOnClickListener(this);
        findViewById(R.id.btn_send_flag_ongoing_event_notification).setOnClickListener(this);
        findViewById(R.id.btn_send_flag_auto_cancecl_notification).setOnClickListener(this);

        mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_remove_all_notification:
                //移除当前 Context 下所有 Notification,包括 FLAG_NO_CLEAR 和 FLAG_ONGOING_EVENT
                mNotificationManager.cancelAll();
                break;
            case R.id.btn_send_notification:
                //发送一个 Notification,此处 ID = 1
                sendNotification();
                break;
            case R.id.btn_remove_notification:
                //移除 ID = 1 的 Notification,注意:该方法只针对当前 Context。
                mNotificationManager.cancel(DEFAULT_NOTIFICATION_ID);
                break;
            case R.id.btn_send_notification_with_tag:
                //发送一个 ID = 1 并且 TAG = littlejie 的 Notification
                //注意:此处发送的通知与 sendNotification() 发送的通知并不冲突
                //因为此处的 Notification 带有 TAG
                sendNotificationWithTag();
                break;
            case R.id.btn_remove_notification_with_tag:
                //移除一个 ID = 1 并且 TAG = littlejie 的 Notification
                //注意:此处移除的通知与 NotificationManager.cancel(int id) 移除通知并不冲突
                //因为此处的 Notification 带有 TAG
                mNotificationManager.cancel(NOTIFICATION_TAG, DEFAULT_NOTIFICATION_ID);
                break;
            case R.id.btn_send_ten_notification:
                //连续发十条 Notification
                sendTenNotifications();
                break;
            case R.id.btn_send_flag_no_clear_notification:
                //发送 ID = 1, flag = FLAG_NO_CLEAR 的 Notification
                //下面两个 Notification 的 ID 都为 1,会发现 ID 相等的 Notification 会被最新的替换掉
                sendFlagNoClearNotification();
                break;
            case R.id.btn_send_flag_auto_cancecl_notification:
                sendFlagOngoingEventNotification();
                break;
            case R.id.btn_send_flag_ongoing_event_notification:
                sendFlagAutoCancelNotification();
                break;
        }
    }

    /**
     * 发送最简单的通知,该通知的ID = 1
     */
    private void sendNotification() {
        //这里使用 NotificationCompat 而不是 Notification ,因为 Notification 需要 API 16 才能使用
        //NotificationCompat 存在于 V4 Support Library
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("Send Notification")
                .setContentText("Hi,My id is 1");
        mNotificationManager.notify(DEFAULT_NOTIFICATION_ID, builder.build());
    }

    /**
     * 使用notify(String tag, int id, Notification notification)方法发送通知
     * 移除对应通知需使用 cancel(String tag, int id)
     */
    private void sendNotificationWithTag() {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("Send Notification With Tag")
                .setContentText("Hi,My id is 1,tag is " + NOTIFICATION_TAG);
        mNotificationManager.notify(NOTIFICATION_TAG, DEFAULT_NOTIFICATION_ID, builder.build());
    }

    /**
     * 循环发送十个通知
     */
    private void sendTenNotifications() {
        for (int i = 0; i < 10; i++) {
            NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle("Send Notification Batch")
                    .setContentText("Hi,My id is " + i);
            mNotificationManager.notify(i, builder.build());
        }
    }

    /**
     * 设置FLAG_NO_CLEAR
     * 该 flag 表示该通知不能被状态栏的清除按钮给清除掉,也不能被手动清除,但能通过 cancel() 方法清除
     * Notification.flags属性可以通过 |= 运算叠加效果
     */
    private void sendFlagNoClearNotification() {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("Send Notification Use FLAG_NO_CLEAR")
                .setContentText("Hi,My id is 1,i can't be clear.");
        Notification notification = builder.build();
        //设置 Notification 的 flags = FLAG_NO_CLEAR
        //FLAG_NO_CLEAR 表示该通知不能被状态栏的清除按钮给清除掉,也不能被手动清除,但能通过 cancel() 方法清除
        //flags 可以通过 |= 运算叠加效果
        notification.flags |= Notification.FLAG_NO_CLEAR;
        mNotificationManager.notify(DEFAULT_NOTIFICATION_ID, notification);
    }

    /**
     * 设置FLAG_AUTO_CANCEL
     * 该 flag 表示用户单击通知后自动消失
     */
    private void sendFlagAutoCancelNotification() {
        //设置一个Intent,不然点击通知不会自动消失
        Intent resultIntent = new Intent(this, MainActivity.class);
        PendingIntent resultPendingIntent = PendingIntent.getActivity(
                this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("Send Notification Use FLAG_AUTO_CLEAR")
                .setContentText("Hi,My id is 1,i can be clear.")
                .setContentIntent(resultPendingIntent);
        Notification notification = builder.build();
        //设置 Notification 的 flags = FLAG_NO_CLEAR
        //FLAG_AUTO_CANCEL 表示该通知能被状态栏的清除按钮给清除掉
        //等价于 builder.setAutoCancel(true);
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        mNotificationManager.notify(DEFAULT_NOTIFICATION_ID, notification);
    }

    /**
     * 设置FLAG_ONGOING_EVENT
     * 该 flag 表示发起正在运行事件(活动中)
     */
    private void sendFlagOngoingEventNotification() {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("Send Notification Use FLAG_ONGOING_EVENT")
                .setContentText("Hi,My id is 1,i can't be clear.");
        Notification notification = builder.build();
        //设置 Notification 的 flags = FLAG_NO_CLEAR
        //FLAG_ONGOING_EVENT 表示该通知通知放置在正在运行,不能被手动清除,但能通过 cancel() 方法清除
        //等价于 builder.setOngoing(true);
        notification.flags |= Notification.FLAG_ONGOING_EVENT;
        mNotificationManager.notify(DEFAULT_NOTIFICATION_ID, notification);
    }    
}

给Notification设置PendingIntent

PendingIntent可以通过setContentIntent(PendingIntent intent)这个方法进行设置

当我们点击通知栏时想跳转一个Activity或者开启一个service时,就可以通过设置PendingIntent达成

PendingIntent 是 Android 系统管理并持有的用于描述和获取原始数据的对象的标志(引用)。也就是说,即便创建该PendingIntent对象的进程被杀死了,这个PendingItent对象在其他进程中还是可用的。
日常使用中的短信、闹钟等都用到了 PendingIntent。

PendingIntent 主要可以通过以下三种方式获取:

//获取一个用于启动 Activity 的 PendingIntent 对象
public static PendingIntent getActivity(Context context, int requestCode, Intent intent, int flags);

//获取一个用于启动 Service 的 PendingIntent 对象
public static PendingIntent getService(Context context, int requestCode, Intent intent, int flags);

//获取一个用于向 BroadcastReceiver 广播的 PendingIntent 对象
public static PendingIntent getBroadcast(Context context, int requestCode, Intent intent, int flags)

PendingIntent 具有以下几种 flag:

FLAG_CANCEL_CURRENT:如果当前系统中已经存在一个相同的 PendingIntent 对象,那么就将先将已有的 PendingIntent 取消,然后重新生成一个 PendingIntent 对象。

FLAG_NO_CREATE:如果当前系统中不存在相同的 PendingIntent 对象,系统将不会创建该 PendingIntent 对象而是直接返回 null 。

FLAG_ONE_SHOT:该 PendingIntent 只作用一次。

FLAG_UPDATE_CURRENT:如果系统中已存在该 PendingIntent 对象,那么系统将保留该 PendingIntent 对象,但是会使用新的 Intent 来更新之前 PendingIntent 中的 Intent 对象数据,例如更新 Intent 中的 Extras 。

自定义Notification

Android系统允许使用RemoteViews来自定义通知。自定义普通视图通知高度限制为64dp,大视图通知高度限制为256dp。同时,建议自定义通知尽量简单,以提高兼容性。
自定义通知需要做如下操作:1、创建自定义通知布局2、使用RemoteViews定义通知组件,如图标、文字等3、调用setContent()将RemoteViews对象绑定到NotificationCompat.Builder4、同正常发送通知流程

注意: 避免为通知设置背景,因为兼容性原因,有些文字可能看不清。
关于自定义Notification兼容问题,请阅读我的另一篇博客 Android通知栏版本兼容解决方案

例子:

RemoteViews notifactionView = new RemoteViews(mContext.getPackageName(),
        R.layout.cl_screen_notification);
mBuilder.setContent(notifactionView);
notifactionView.setOnClickPendingIntent(R.id.cl_screen_notification, pendingIntent);
Bitmap pluginIcon = drawableToBitmap(pluginDrawable);
LogUtils.d("myl", "获得icon" + pluginIcon);
notifactionView.setImageViewBitmap(R.id.cl_plugin_icon, pluginIcon);
notifactionView.setTextViewText(R.id.dl_plugin_msg, pluginContent);
Notification notification = mBuilder.build();
int id = 199;
LogUtils.d(TAG, "创建通知");
mNotificationManager.notify(id, notification);


Notification的各种样式

1) BigText样式(Android 4.1以上)
a) 最大高度一般为256dp
b) 不是最新的通知时默认为折叠状态
c) 不设置SummaryText的话,展开后最下面一行的内容会消失

例子:

private void showBigViewText() {
         NotificationCompat.BigTextStyle textStyle = new BigTextStyle();
         textStyle
                 .setBigContentTitle("BigContentTitle")
                 .setSummaryText("SummaryText")
                 .bigText(
                         "I am Big Text");
         Notification notification = new NotificationCompat.Builder(context)
                 .setLargeIcon(icon).setSmallIcon(R.drawable.ic_launcher)
                 .setTicker("showBigView_Text").setContentInfo("contentInfo")
                 .setContentTitle("ContentTitle").setContentText("ContentText")
                 .setStyle(textStyle)
                 .setAutoCancel(true).setDefaults(Notification.DEFAULT_ALL)
                 .build();
         manager.notify(NOTIFICATION_ID_2, notification);
     }

2) Inbox样式
a) 高度一般为256dp
b) 不是最新的通知时默认为折叠状态
c) 不设置SummaryText的话,展开后最下面一行的内容会消失
例子:

 private void showBigViewInbox() {
         NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
         inboxStyle.setBigContentTitle("BigContentTitle").setSummaryText(
                 "SummaryText");
         for (int i = 0; i < 5; i++)
             inboxStyle.addLine("news:" + i);
         Notification notification = new NotificationCompat.Builder(context)
                 .setLargeIcon(icon).setSmallIcon(R.drawable.ic_launcher)
                 .setTicker("showBigView_Inbox").setContentInfo("contentInfo")
                 .setContentTitle("ContentTitle").setContentText("ContentText")
                 .setStyle(inboxStyle)
                 .setAutoCancel(true).setDefaults(Notification.DEFAULT_ALL)
                 .build();
         manager.notify(NOTIFICATION_ID_4, notification);
     }

3) BigPicture样式
a) 高度一般为256dp
b) 不是最新的通知时为默认折叠状态
c) 不设置SummaryText的话,展开后第二行字的内容会消失

例子:

private void showBigViewPic() {
         NotificationCompat.BigPictureStyle pictureStyle = new BigPictureStyle();
         pictureStyle.setBigContentTitle("BigContentTitle")
                 .setSummaryText("SummaryText").bigPicture(icon);
         Notification notification = new NotificationCompat.Builder(context)
                 .setLargeIcon(icon).setSmallIcon(R.drawable.ic_launcher)
                 .setTicker("showBigView_Pic").setContentInfo("contentInfo")
                 .setContentTitle("ContentTitle").setContentText("ContentText")
                 .setStyle(pictureStyle)
                 .setAutoCancel(true).setDefaults(Notification.DEFAULT_ALL)
                 .build();
         manager.notify(NOTIFICATION_ID_3, notification);
     }

4) 折叠式Notification
折叠式Notification是一种自定义视图的Notification,用来显示长文本和一些自定义的布局的场景。它有两种状态,一种是普通状态下的视图,一种是展开状态下的视图。和普通Notification不同的是,我们需要自定义的视图,而这个视图显示的进程和我们创建视图的进程不再一个进程,所以我们需要使用RemoteViews,首先要使用RemoteViews来创建我们的自定义视图:

//用RemoteViews来创建自定义Notification视图
RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.view);

视图的布局文件:

<?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="100dp"
    android:background="@drawable/fold"
    android:orientation="horizontal">
<ImageView
    android:id="@+id/iv_image"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:src="@drawable/fold"
    />

    <TextView
        android:id="@+id/tv_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        android:layout_marginLeft="150dp"
        android:text="展开后的视图"
        android:textColor="@color/colorPrimaryDark"/>
</LinearLayout>

把自定义视图赋值给Notification展开时的视图

//指定展开时的视图
notification.bigContentView = remoteViews;

也可以把自定义视图赋值给Notification普通状态时的视图

//指定普通状态时的视图
notification.contentView = remoteViews;

折叠式Notification完整代码:

 Notification.Builder builder = new Notification.Builder(this);
        Intent mIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://blog.csdn.net/itachi85/"));
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, mIntent, 0);
        builder.setContentIntent(pendingIntent);
        builder.setSmallIcon(R.drawable.foldleft);
        builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.lanucher));
        builder.setAutoCancel(true);
        builder.setContentTitle("折叠式通知");
        //用RemoteViews来创建自定义Notification视图
        RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.view_fold);
        Notification notification = builder.build();
        //指定展开时的视图
        notification.bigContentView = remoteViews;
        notificationManager.notify(1, notification);

5) 悬挂式Notification (5.0新增)
悬挂式Notification是android5.0新增加的方式,悬挂式Notification不需要下拉通知栏就直接显示出来悬挂在屏幕上方并且焦点不变仍在用户操作的界面因此不会打断用户的操作,过几秒就会自动消失。他需要调用setFullScreenIntent来将Notification变为悬挂式Notification

//如果描述的PendingIntent已经存在,则在产生新的Intent之前会先取消掉当前的
        PendingIntent hangPendingIntent = PendingIntent.getActivity(this, 0, hangIntent, PendingIntent.FLAG_CANCEL_CURRENT);
        builder.setFullScreenIntent(hangPendingIntent, true);

悬挂式Notification完整代码:

Notification.Builder builder = new Notification.Builder(this);
        Intent mIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://blog.csdn.net/itachi85/"));
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, mIntent, 0);
        builder.setContentIntent(pendingIntent);
        builder.setSmallIcon(R.drawable.foldleft);
        builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.lanucher));
        builder.setAutoCancel(true);
        builder.setContentTitle("悬挂式通知");
        //设置点击跳转
        Intent hangIntent = new Intent();
        hangIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        hangIntent.setClass(this, MyNotificationActivity.class);
        //如果描述的PendingIntent已经存在,则在产生新的Intent之前会先取消掉当前的
        PendingIntent hangPendingIntent = PendingIntent.getActivity(this, 0, hangIntent, PendingIntent.FLAG_CANCEL_CURRENT);
        builder.setFullScreenIntent(hangPendingIntent, true);
        notificationManager.notify(2, builder.build());

这里写图片描述

6) 锁屏通知
Android 5.0(API level 21)开始,通知可以显示在锁屏上。用户可以通过设置选择是否允许敏感的通知内容显示在安全的锁屏上。你的应用可以通过setVisibility()控制通知的显示等级:

VISIBILITY_PRIVATE : 显示基本信息,如通知的图标,但隐藏通知的全部内容
VISIBILITY_PUBLIC : 显示通知的全部内容
VISIBILITY_SECRET : 不显示任何内容,包括图标

  builder.setVisibility(Notification.VISIBILITY_PUBLIC);

最后,推送一下自己的微信公众号,喜欢的同学可以关注。
在这里插入图片描述

Android 10 通知-源码解析 /frameworks/base/packages/SystemUI/src/com/android/systemui/util/NotificationChannels.java //通知弹出屏幕 106 /** 107 * Set up screenshot channel, respecting any previously committed user settings on legacy 108 * channel. 109 * @return 110 . 阅读详情

相关推荐

Notification和NotificationManagerService原理解析

本篇代码基于原生Android P 一.通知的基本使用 通知栏消息是应用开发中十分常见和重要的一项功能。在Android O之后,增加了NotificationChannel的新特性,相同channel的通知拥有同样的特性,例如优先级,声音,振动,LED灯等等。这个特性使得相同属性的通知能够集中被管理,同时用户自己可以在应用的通知管理中手动修改channel的某项特性,这样给了用户一定的自主选...

cbzcbzcbzcbz的博客 2520

安卓通知与NotificationCompat.Builder

安卓更新挺快,以至于之前学的关于通知的使用方法都过时了 现在重新再写个文章记录一下 创建通知 Android 3.0 (API level 11)之前,使用new Notification()方式创建通知: NotificationManager mNotifyMgr = (NotificationManager) getSystemService(NOTIF

鬼妖妖的博客 6911

基于WSP/WTP的MMS传输(7)——MMS Notification 解析

<br /><br /> 七 MMS Notification 解析<br /> <br />    之所以把MMS Notification 放在单独的一节是由于它的特殊性,前面提到过,MMS Notification 是由SMSC (短息服务中心)以PUSH 通知的方式发给接收方的,即MMS Notification 是一条短息,不同于普通的短息,MMS Notification 的编码是WSP +MMS PDU Header 的结构,里面最重要的信息就是Content-Location ,它指出了彩信

jccmusi的专栏 5225

Android开发—Notification控件,使用 Builder 构造器来创建 Notification 对象,控件Toolbar常用属性详解

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

WZY22502701的博客 1885

Android5.x Notification应用解析

Notification可以让我们在获得消息的时候,在状态栏,锁屏界面来显示相应的信息,很难想象如果没有Notification,那我们的qq和微信以及其他应用没法主动通知我们,我们就需要时时的看手机来检查是否有新的信息和提醒着实让人烦心,也体现出Notification重要性。这里会介绍三种Notification,分别是普通的Notification,折叠式Notification和悬挂式Not

Android进阶三部曲 - 刘望舒 2万+

Android开发中使用通知的方法及NotificationCompat.Builder的使用和引导用户开启通知编程

为了简化通知的创建和管理过程,Android提供了NotificationCompat.Builder类,它是一个兼容性类,可以在不同版本的Android系统上使用相同的API。这里的channelId是通知渠道的ID,channelName是通知渠道的名称,importance指定了通知的重要性级别。在使用通知功能时,有时候用户会关闭应用的通知权限,为了确保通知能正常显示,我们需要引导用户开启通知。notificationId是通知的唯一标识符,每个通知应该有不同的标识符。三、引导用户开启通知。

ByteKnight的博客 578

Notification使用详情解析

Notification在Android中使用的频率可以说是非常高的,本篇博客,我将围绕着Notification的各方面进行解析,使大家对Notification有更好的认识。 Notification的使用步骤 1.获取NotificationManager NotificationManager mNotificationManager = (NotificationManag

qq_21355765的博客 462

深入解析 Fiori Launchpad Notification:架构、配置与用户体验全景

开发者可继承接口,在注册自研 Provider,利用实例化消息;若想批量推送,可用API (

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 451

android notification 大图,Android Notification 史上最全面的解析

关于Notification那些事,最近一直在弄这块,抽了点时间总结一下,做了一个Demo,废话不多说,先上图看效果通知.png通知2.png在Android 3.0 (API level 11)之前,使用new Notification()方式创建通知:String tickerText = "tikcker内容";String title ="标题";String content ="内容";...

weixin_39773215的博客 655

计算机视觉之ResNet

RestNet是2015年由微软团队提出的,在当时获得分类任务,目标检测,图像分割第一名。该论文的四位作者何恺明、张祥雨、任少卿和孙剑如今在人工智能领域里都是响当当的名字,当时他们都是微软亚研的一员。实验结果显示,残差网络更容易优化,并且加深网络层数有助于提高正确率。在ImageNet上使用152层的残差网络(VGG net的8倍深度,但残差网络复杂度更低)。对这些网络使用集成方法实现了3.75%的错误率。获得了ILSVRC 2015竞赛的第一名。原文链接这是一篇计算机视觉领域的经典论文。

十年以上架构设计经验,专注于软件架构和人工智能领域,对机器视觉、NLP、音视频等领域都有涉猎 2万+

IAR编译相同工程生产hex文件checksum不一致问题

IAR Checksum

xqw19891201的博客 1392

android notification完全解析【转】

转自:http://www.itnose.net/detail/6169442.html Notifications in Android 4.4 and Lower notification是很重要的部分,它与service,BroadcastReceiver,Intent等密切相关,很好地使用notification可以使你的app的活跃度相对于没有notification 的app大增。...

weixin_33919950的博客 92

ArcGIS Pro 3.0 水文分析实战:用DEM数据模拟城市内涝,手把手教你生成淹没范围图

本文详细介绍了如何使用ArcGIS Pro 3.0进行水文分析,通过DEM数据模拟城市内涝并生成淹没范围图。从数据准备、核心分析流程优化到成果可视化,手把手教你掌握关键技巧,如动态流量阈值设定和淹没区三维模拟,帮助城市规划与应急管理部门精准预测积水范围。

weixin_42531925的博客 248

notification源码分析_源码解析篇:Android深入理解Notification机制

本文需要解决的问题笔者最近正在做一个项目,里面需要用到 「Android Notification」 机制来实现某些特定需求。我正好通过这个机会研究一下 「Android Notification」 相关的发送逻辑和接收逻辑,以及整理相关的笔记。我研究 「Notification 机制」的目的是解决以下我在使用过程中所思考的问题:我们创建的 Notification 实例最终以什么样的方...

weixin_35034072的博客 964

Py6S安装失败?手把手教你解决‘6S executable not found‘错误

本文详细解析了Py6S安装过程中常见的'6S executable not found'错误,提供了从MinGW-w64安装到Fortran编译器配置的完整解决方案。通过优化编译环境和进阶技巧,帮助用户高效完成大气辐射传输建模,提升科学计算效率。

x1y2z的博客 657

使用Power Automate在Calendar中创建会议

Power Automate提供了一个create event操作,用来在calendar日历中创建一个会议。这里使用的触发器是SharePoint列表触发器,每当在列表中新建一个item,就会触发工作流,然后在所有参会人员的日历中创建一个会议,并且发邮件给参会人员。 列表结构如下,包含会议主题,会议室,开始时间,结束时间和参会人员信息。其中attendees为参会人员,包含多值的用户列。 P...

shrenk的专栏 1862

解决Element Plus Notification组件HTML解析问题:从陷阱到解决方案

Element Plus的Notification(通知)组件是Web应用中常用的交互元素,但在处理HTML内容时常常出现解析异常。本文将深入分析HTML解析功能的实现原理,通过实际案例演示安全配置方法,并提供完整的问题排查流程,帮助开发者避免常见陷阱。 ## 问题现象与安全机制解析 当开发者尝试在Notification中嵌入HTML内容时,常会遇到内容被转义或无法渲染的问题。这一现象源于E...

gitblog_00028的博客 353

运算放大器电路仿真实践:从零实现完整示例

通过一个完整的运算放大器电路仿真示例,深入掌握电路仿真的关键步骤与技巧,帮助电子爱好者和工程师快速上手实际项目设计。

weixin_34725745的博客 1329

Element Plus 中 el-notification 的 TypeScript 类型问题解析

在 Vue 3 生态系统中,Element Plus 作为一款优秀的 UI 组件库,为开发者提供了丰富的组件支持。其中,el-notification 组件常用于显示全局通知消息。然而,在实际开发中,我们发现该组件在 TypeScript 类型定义上存在一个值得注意的问题。 ## 问题背景 当开发者尝试使用 el-notification 组件并传入应用上下文(appContext)作为第二个...

gitblog_00874的博客 440

iSLIP算法实战:如何用Python模拟交换机优先级匹配(附完整代码)

本文详细介绍了如何使用Python实现iSLIP算法,模拟交换机优先级匹配过程。通过核心的指针滑动逻辑和迭代循环策略,构建了一个完整的iSLIP算法模拟器,并加入可视化模块以直观展示匹配过程。文章还提供了完整的代码框架和性能优化建议,适合网络工程师和Python开发者直接集成到测试环境中。

weixin_29313239的博客 260

高速PCB设计中的一些常用规则

目前,高速PCB产品设计中,高速接口的应用日益普及,对于复杂的设计而言,高速走线就如同“蜘蛛网”一样密布在PCB各处,因此,在进行PCB检查及评审时,必要的高速PCB设计经验法则及规则是工程师开展工作必不可少的知识储备。

一只豌豆象的博客 3428
上一篇: 一篇博客理解Recyclerview的使用
下一篇: 一篇博客让你了解RxJava
进击的代码家
进击的代码家 领域专家: 算法与数据结构技术领域 领域专家: 算法与数据结构技术领域
博客等级 码龄13年 3265粉丝 515原创
评论 19
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

进击的代码家

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值