GVKun编程网logo

详解Android中Notification的使用方法(android notificationmanager)

3

在这里,我们将给大家分享关于详解Android中Notification的使用方法的知识,让您更了解androidnotificationmanager的本质,同时也会涉及到如何更有效地Android

在这里,我们将给大家分享关于详解Android中Notification的使用方法的知识,让您更了解android notificationmanager的本质,同时也会涉及到如何更有效地Android Notification 使用方法详解、android Notification 的一个简单应用(在 Notification 中嵌入一个进度条,并且这个 Notification 点击消失但不会跳转)、Android Notification 的使用、Android Notification 详解的内容。

本文目录一览:

详解Android中Notification的使用方法(android notificationmanager)

详解Android中Notification的使用方法(android notificationmanager)

      在消息通知的时候,我们经常用到两个控件Notification和Toast。特别是重要的和需要长时间显示的信息,用Notification最合适不过了。他可以在顶部显示一个图标以标示有了新的通知,当我们拉下通知栏的时候,可以看到详细的通知内容。
      最典型的应用就是未看短信和未接来电的显示,还有QQ微信,我们一看就知道有一个未接来电或者未看短信,收到QQ离线信息。同样,我们也可以自定义一个Notification来定义我们自己的程序想要传达的信息。

Notification我把他分为两种,一种是默认的显示方式,另一种是自定义的,今天为大家讲述默认的显示方式
1、程序框架结构图如下


2、布局文件 main.xml 源码如下

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
 android:orientation="vertical" 
 android:layout_width="fill_parent" 
 android:layout_height="fill_parent" 
 > 
<TextView  
 android:layout_width="fill_parent"  
 android:layout_height="wrap_content"  
 android:gravity="center" 
 android:textColor="#EEE" 
 android:textandroid:textSize="25sp" 
 android:text="NotificationDemo实例" /> 
<Button 
 android:id="@+id/btnSend" 
 android:text="send notification" 
 android:layout_width="wrap_content" 
 android:layout_height="wrap_content" 
 android:layout_gravity="center"/>  
</LinearLayout> 

3、MainActivity.java源码如下:

package com.andyidea.notification; 
 
import android.app.Activity; 
import android.content.Intent; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.Button; 
 
public class MainActivity extends Activity { 
 private Button btnSend; 
  
 //定义broadcastReceiver的action 
 private static final String NotificationDemo_Action = "com.andyidea.notification.NotificationDemo_Action"; 
  
 /** Called when the activity is first created. */ 
 @Override 
 public void onCreate(Bundle savedInstanceState) { 
  super.onCreate(savedInstanceState); 
  setContentView(R.layout.main); 
   
  btnSend = (Button)findViewById(R.id.btnSend); 
  btnSend.setonClickListener(new View.OnClickListener() { 
   @Override 
   public void onClick(View v) { 
    Intent intent = new Intent(); 
    intent.setAction(NotificationDemo_Action); 
    sendbroadcast(intent); 
   } 
  }); 
 } 
  
} 

4、布局文件 secondlayou.xml 源码如下:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout 
 xmlns:android="http://schemas.android.com/apk/res/android" 
 android:orientation="vertical" 
 android:layout_width="fill_parent" 
 android:layout_height="fill_parent"> 
 <TextView  
 android:layout_width="fill_parent"  
 android:layout_height="wrap_content"  
 android:gravity="center" 
 android:textColor="#EEE" 
 android:textandroid:textSize="25sp" 
 android:text="显示通知界面" /> 
<Button 
 android:id="@+id/btnCancel" 
 android:text="cancel notification" 
 android:layout_width="wrap_content" 
 android:layout_height="wrap_content" 
 android:layout_gravity="center" />  
</LinearLayout> 

5、SecondActivity.java源码如下:

package com.andyidea.notification; 
 
import android.app.Activity; 
import android.app.Notification; 
import android.app.notificationmanager; 
import android.app.PendingIntent; 
import android.content.Intent; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.Button; 
 
public class SecondActivity extends Activity { 
 
 private Button btnCancel; 
 //声明Notification 
 private Notification notification; 
 //声明notificationmanager 
 private notificationmanager mNotification; 
 //标识Notification的ID 
 private static final int ID = 1; 
  
 @Override 
 protected void onCreate(Bundle savedInstanceState) { 
  super.onCreate(savedInstanceState); 
  setContentView(R.layout.secondlayout); 
   
  btnCancel = (Button)findViewById(R.id.btnCancel); 
  //怎样获得notificationmanager的实例? 
  String service = NOTIFICATION_SERVICE; 
  mNotification = (notificationmanager)getSystemService(service); 
   
  //获得Notification的实例 
  notification = new Notification(); 
   
  //设置该图标 会在状态栏显示 
  int icon = notification.icon = android.R.drawable.stat_sys_phone_call; 
  //设置提示信息 
  String tickerText = "Test Notification"; 
  //设置显示时间 
  long when = System.currentTimeMillis(); 
  notification.icon = icon; 
  notification.tickerText = tickerText; 
  notification.when = when; 
   
  Intent intent = new Intent(this,MainActivity.class); 
  PendingIntent pi = PendingIntent.getActivity(this,intent,0); 
  notification.setLatestEventInfo(this,"消息","SMS Android",pi); 
  mNotification.notify(ID,notification); 
   
  btnCancel.setonClickListener(new View.OnClickListener() { 
   @Override 
   public void onClick(View v) { 
    mNotification.cancel(ID); //--->取消通知 
   } 
  }); 
 } 
  
} 

6、NotificationReceiver.java源码如下:

package com.andyidea.notification; 
 
import com.andyidea.notification.SecondActivity; 
 
import android.content.broadcastReceiver; 
import android.content.Context; 
import android.content.Intent; 
 
public class NotificationReceiver extends broadcastReceiver { 
 
 @Override 
 public void onReceive(Context context,Intent intent) { 
  //实例化Intent 
  Intent i = new Intent(); 
  //在新任务中启动Activity 
  i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
  //设置Intent启动的组件名称 
  i.setClass(context,SecondActivity.class); 
  //启动Activity,显示通知 
  context.startActivity(i); 
 } 
 
} 

7、程序运行效果如下:

以上就是针对Android中Notification使用方法进行的详细介绍,希望对大家的学习有所启发,帮助大家更好地学习Android软件编程。

Android Notification 使用方法详解

Android Notification 使用方法详解

Android Notification 使用方法详解

用TaskStackBuilder来获取PendingIntent处理点击跳转到别的Activity,首先是用一般的PendingIntent来进行跳转。

mBuilder = new NotificationCompat.Builder(this).setContent(view) 
    .setSmallIcon(R.drawable.icon).setTicker("新资讯") 
    .setWhen(System.currentTimeMillis()) 
    .setongoing(false) 
    .setAutoCancel(true); 
Intent intent = new Intent(this,NotificationShow.class); 
 PendingIntent pendingIntent = PendingIntent.getActivity(this,intent,PendingIntent.FLAG_UPDATE_CURRENT); 
mBuilder.setContentIntent(pendingIntent); 

直接用PendingIntent来跳转到NotificationShow,在运行效果上来看,首先发送了一条Notification到通知栏上,然后这时,我退出程序,即MainActivity已经不存在了,回到home主菜单,看到Notification仍然存在,当然,我们还没有点击或者cancel它,现在去点击Notification,跳转到NotificationShow界面,然后我们按下Back键,发现直接回到主界面了。现在大多数android应用都是在通知栏中如果有Notification通知的话,点击它,然后会直接跳转到对应的应用程序的某个界面,这时如果回退,即按下Back键,会返回到该应用程序的主界面,而不是系统的主界面。所以用上面这种PendingIntent的做法达不到目的。这里我们使用TaskStackBuilder来做。

mBuilder = new NotificationCompat.Builder(this).setContent(view) 
        .setSmallIcon(R.drawable.icon).setTicker("新资讯") 
        .setWhen(System.currentTimeMillis()) 
        .setongoing(false) 
        .setAutoCancel(true); 
    Intent intent = new Intent(this,NotificationShow.class); 
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); 
    stackBuilder.addParentStack(NotificationShow.class); 
    stackBuilder.addNextIntent(intent); 
    PendingIntent pendingIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT); 
//    PendingIntent pendingIntent = PendingIntent.getActivity(this,//    intent,PendingIntent.FLAG_UPDATE_CURRENT); 
    mBuilder.setContentIntent(pendingIntent); 

        显示用TaskStackBuilder.create(this)一个stackBuilder实例,接下来addParentStack();关于这个方法,我们查一下官方api文档:Add the activity parent chain as specified by the parentActivityName attribute of the activity (or activity-alias) element in the application's manifest to the task stack builder. 这句话是说添加一个activity,与这个activity的manifest文件中的parentActivityName的属性相关联。

那么我们就在manifest文件中添加这个属性

<activity 
  android:name="com.shulf.notificationtest.NotificationShow" 
  android:parentActivityName=".MainActivity" > 
</activity> 

让它的parentActivity为MainActivity,也就是说在NotificationShow这个界面点击回退时,会跳转到MainActivity这个界面,而不是像上面一样直接回到了程序的主菜单。运行一下,最后效果确实是这样。

以上实用Android Notification的实例详解,如有疑问请留言或者到本站社区交流讨论,本站关于Android开发的文章还有很多,希望大家搜出查阅,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

android Notification 的一个简单应用(在 Notification 中嵌入一个进度条,并且这个 Notification 点击消失但不会跳转)

android Notification 的一个简单应用(在 Notification 中嵌入一个进度条,并且这个 Notification 点击消失但不会跳转)

   网上很多的例子都是直接获取 Notification 对象来设置一个通知,其实 Notification 跟 Dialog 一样,也有自己的 Builder,可以用 builder 对象来设置一个 Notification

    这个例子是在 Notification 中嵌入一个进度条,并且这个 Notification 点击消失但不会跳转(跟 android 的 vcard 文件导入时弹出的 Notification 一样)

    NotificationManager mNotificationManager = (NotificationManager)
                context.getSystemService(Context.NOTIFICATION_SERVICE);
        Notification.Builder builder = new Notification.Builder(context);
        builder.setOngoing(true);
        builder.setProgress (total, current, false);// 设置进度条,false 表示是进度条,true 表示是个走马灯
        builder.setTicker (title);// 设置 title
        builder.setWhen(System.currentTimeMillis());
        builder.setContentTitle (content);// 设置内容
        builder.setAutoCancel (true);// 点击消失
        builder.setSmallIcon(R.drawable.upload);
        builder.setContentIntent (PendingIntent.getActivity (context, 0, new Intent (), 0));// 这句和点击消失那句是 “Notification 点击消失但不会跳转” 的必须条件,如果只有点击消失那句,这个功能是不能实现的

        Notification noti = builder.getNotification();
        mNotificationManager.notify(id,noti);

希望这个例子对其他人有点用,因为我特曾为这个功能苦恼过,呵呵!


Android Notification 的使用

Android Notification 的使用

今天使用 4.0.3 使用

Notification notification2 = new Notification(R.drawable.advise2,  
"通知测试",
System.currentTimeMillis()); notification2.setLatestEventInfo(getActivity(), "testTitle", "testContent", null);

结果 androidstudio 报错,setLatestEventInfo 该方法找不到,经过查证官方在 API Level 11 中,该函数已经被替代,不推荐使用了。所以在 4.0.3 平台也就是 API Level 15 中,使用 Notification 的 setLatestEventInfo () 函数时,显示 setLatestEventInfo () 效果。建议使用 Notification.Builder 来创建 notification 实例

Notification.Builder builder1 = new Notification.Builder(MainActivity.this);
builder1.setSmallIcon(R.drawable.advise2); //设置图标
builder1.setTicker("显示第二个通知"); 
builder1.setContentTitle("通知"); //设置标题
builder1.setContentText("点击查看详细内容"); //消息内容
builder1.setWhen(System.currentTimeMillis()); //发送时间
builder1.setDefaults(Notification.DEFAULT_ALL); //设置默认的提示音,振动方式,灯光
builder1.setAutoCancel(true);//打开程序后图标消失
Intent intent =new Intent (MainActivity.this,Center.class);
PendingIntent pendingIntent =PendingIntent.getActivity(MainActivity.this, 0, intent, 0);
builder1.setContentIntent(pendingIntent);
Notification notification1 = builder1.build();
notificationManager.notify(124, notification1); // 通过通知管理器发送通知

如果该通知只是起到 “通知” 的作用,不希望用户点击后有相应的跳转,那么,intent,pendingIntent 这几行代码可以不写

Notification.Builder builder = new Notification.Builder(MainActivity.this);
builder.setSmallIcon(R.drawable.advise);
 builder.setTicker("显示第一个通知");
builder.setContentTitle("第一个通知");
builder.setContentText("每天进步一点点");
builder.setWhen(System.currentTimeMillis()); //发送时间
builder.setDefaults(Notification.DEFAULT_ALL);
Notification notification = builder.build();
notificationManager.notify(123, notification);

第一个具有点击提示有跳转功能,后面一个没有跳转功能,只是提示作用

以下借鉴其他博主的总结:
    低于 API Level 11 版本,也就是 Android 2.3.3 以下的系统中,setLatestEventInfo () 函数是唯一的实现方法。前面的有关属性设置这里就不再提了,网上资料很多。

Intent  intent = new Intent(this,MainActivity);  
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_ONE_SHOT);  
notification.setLatestEventInfo(context, title, message, pendingIntent);          
manager.notify(id, notification); 

    高 于 API Level 11,低于 API Level 16 (Android 4.1.2) 版本的系统中,可使用 Notification.Builder 来构造函数。但要使用 getNotification () 来使 notification 实现。此时,前面版本在 notification 中设置的 Flags,icon 等属性都已经无效,要在 builder 里面设置。

Notification.Builder builder = new Notification.Builder(context)  
            .setAutoCancel(true)  
            .setContentTitle("title")  
            .setContentText("describe")  
            .setContentIntent(pendingIntent)  
            .setSmallIcon(R.drawable.ic_launcher)  
            .setWhen(System.currentTimeMillis())  
            .setOngoing(true);  
notification=builder.getNotification(); 

    高于 API Level 16 的版本,就可以用 Builder 和 build () 函数来配套的方便使用 notification 了。

Notification notification = new Notification.Builder(context)    
         .setAutoCancel(true)    
         .setContentTitle("title")    
         .setContentText("describe")    
         .setContentIntent(pendingIntent)    
         .setSmallIcon(R.drawable.ic_launcher)    
         .setWhen(System.currentTimeMillis())    
         .build();  

    【注意点】:
    在构造 notification 的时候有很多种写法,但是要注意,用
Notification notification = new Notification();
这种构建方法的时候,一定要加上 notification.icon 这个设置,不然,程序虽然不会报错,但是会没有效果。

Example:Notification 的使用案例:

public class MainActivity extends Activity {

    private Button bt1;
    private NotificationManager notificationManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);

        notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);


        setViews();
        setlisteners();
    }

    private void setlisteners() {
        bt1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 发送通知
                Notification.Builder builder = new Notification.Builder(MainActivity.this);
                builder.setSmallIcon(R.mipmap.ic_launcher);
                builder.setTicker("this is ticker text"); // 通知的ticker内容,当通知刚创建的时候,它会在系统的状态栏一闪而过
                builder.setContentTitle("this is title"); // 通知的标题
                builder.setContentText("this is content"); // 通知内容
                builder.setWhen(System.currentTimeMillis()); // 通知被创建的时间,以毫秒为单位
                builder.setDefaults(Notification.DEFAULT_ALL); // 通知到来的时候,手机会发出振动、播放音乐、led灯亮的提示,具体是什么的提示,由手机的设置决定

                Intent intent = new Intent(MainActivity.this,NotificationActivity.class);
                PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this,0,intent,PendingIntent.FLAG_CANCEL_CURRENT);
                builder.setContentIntent(pendingIntent); // 响应通知的点击事件
                Notification notification = builder.getNotification();
                notificationManager.notify(1, notification);
            }
        });
    }

    private void setViews() {
        bt1 = (Button)findViewById(R.id.bt1);
    }
}

NotificationActivity 通知的点击事件的响应活动:

public class NotificationActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_notification);

        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.cancel(1); // // 取消通知  参数:为创建通知的的通知id
    }
}

Android Notification 详解

Android Notification 详解

Android Notification 通知详细介绍

目录介绍

  • 1.Notification 简单概述
  • 2.Notification 通知用途
  • 3.Notification 的基本操作
  • 3.1 Notification 创建必要的属性
  • 3.2 Notification 简单创建步骤
  • 3.3 关于 setSmallIcon () 与 setLargeIcon () 区别
  • 3.4 Notification 的 Action 属性【交互作用】
  • 3.5 更新 Notification
  • 3.6 取消 Notification
  • 3.7 设置 flag 属性
  • 3.8 设置 Notification 的通知效果
  • 3.9 设置自定义 Notification 通知栏布局
  • 4.Notification 相关属性说明
  • 4.1 PendingIntent 说明
  • 4.2 创建返回栈 PendingIntent
  • 4.3 注意要点
  • 5. 部分源码分析思考
  • 5.1 RemoteView 是什么?
  • 5.2 查看源码,了解 Notification 如何创建布局
  • 6. 关于其他
  • 6.1 参考案例
  • 6.2 更新日志
  • v1.0 写于 2016 年 6 月 18 日
  • v1.1 更新于 17 年 12 月 6 日,重新整理笔记
  • 6.3 关于我的博客

0. 备注

  • 建议结合代码,看博客更加高效,项目地址:https://github.com/yangchong211/YCNotification
  • 通知栏截图
  • 案例

  • 说明及截图
  • 模块:新闻,音乐,视频,图片,唐诗宋词,快递,天气,记事本,阅读器等等
  • 接口:七牛,阿里云,天行,干货集中营,极速数据,追书神器等等
  • 持续更新目录说明

1.Notification 简单概述

  • Notification,是一种具有全局效果的通知,可以在系统的通知栏中显示。当 APP 向系统发出通知时,它将先以图标的形式显示在通知栏中。用户可以下拉通知栏查看通知的详细信息。通知栏和抽屉式通知栏均是由系统控制,用户可以随时查看。

2.Notification 通知用途

  • 常见的用途
  • 显示接收到短消息、及时消息等信息(如 QQ、微信、新浪、短信)
  • 显示客户端的推送消息,如广告、优惠、版本更新、推荐新闻等,常用的第三方 SDK 有: JPush 、 个推 、 信鸽 、 网易云信 (偏重 IM) 、 阿里云推送
  • 显示正在进行的事物,例如:后台运行的程序,如音乐播放进度、下载进度等
  • 前两点可以归结为与用户交互,第三点是实时的任务提醒,但不可否认的是,第三点也会与用户交互。

3.Notification 的基本操作

  • 3.1 Notification 创建必要的属性,必须设置

  • 3.1.1 必须添加的属性

  • 小图标,通过 setSmallIcon () 方法设置

  • 标题,通过 setContentTitle () 方法设置

  • 内容,通过 setContentText () 方法设置

  • 3.2 Notification 创建步骤

  • 3.2.1 Notification 的创建主要涉及到 Notification.Builder 、 Notification 、 NotificationManager Notification.Builer : 使用建造者模式构建 Notification 对象。由于 Notification.Builder 仅支持 Android 4.1 及之后的版本,为了解决兼容性问题, Google 在 Android Support v4 中加入了 - NotificationCompat.Builder 类。对于某些在 Android 4.1 之后才特性,即使 NotificationCompat.Builder 支持该方法,在之前的版本中也不能运行。

  • Notification : 通知对应类,保存通知相关的数据。- NotificationManager 向系统发送通知时会用到。

  • NotificationManager : NotificationManager 是通知管理类,它是一个系统服务。调用 NotificationManager 的 notify () 方法可以向系统发送通知。

  • 3.2.2 Notification 创建步骤与代码

// 创建一个NotificationManager的引用
NotificationManager mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
// 定义Notification的各种属性
Notification.Builder mBuilder = new Notification.Builder(this.getApplicationContext())
        .setSound(android.provider.Settings.System.DEFAULT_NOTIFICATION_URI)        //
        .setSmallIcon(R.mipmap.ic_launcher)                                         //设置通知的图标
        .setTicker("有新消息呢")                                                     //设置状态栏的标题
        .setContentTitle("这个是标题")                                               //设置标题
        .setContentText("这个是内容")                                                //消息内容
        .setDefaults(Notification.DEFAULT_ALL)                                      //设置默认的提示音
        .setPriority(Notification.PRIORITY_DEFAULT)                                 //设置该通知的优先级
        .setOngoing(false)                                                          //让通知左右滑的时候不能取消通知
        .setPriority(Notification.PRIORITY_DEFAULT)                                 //设置该通知的优先级
        .setWhen(System.currentTimeMillis())                                        //设置通知时间,默认为系统发出通知的时间,通常不用设置
        .setAutoCancel(true);                                                       //打开程序后图标消失
//处理点击Notification的逻辑
Intent resultIntent = new Intent(this, TestActivity.class);
resultIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);           //添加为栈顶Activity
resultIntent.putExtra("what",5);
PendingIntent resultPendingIntent = PendingIntent.getActivity(this,5,resultIntent,PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
//发送
mNotificationManager.notify(1, mBuilder.build());
//结束广播
//mNotificationManager.cancel(1);
  • 3.3 关于 setSmallIcon () 与 setLargeIcon () 区别

  • 在 NotificationCompat.Builder 中有设置通知的大小图标的两个方法。这两个方法有什么区别呢?

  • 当 setSmallIcon () 与 setLargeIcon () 同时存在时,smallIcon 显示在通知的右下角,largeIcon 显示在左侧

  • 当只设置 setSmallIcon () 时,smallIcon 显示在左侧。看下图你就明白了。

  • 对于部分 ROM ,可能修改过源码,如 MIUI 上通知的大图标和小图标是没有区别的。

  • 效果如图所示: Image.png

  • 3.4 Notification 的 Action 属性

  • 设置一个 Action ,这样就可以直接跳转到 App 的某个 Activity 、启动一个 Service 或者发送一个 Broadcast。否则,Notification 仅仅只能起到通知的效果,而不能与用户交互。

  • 具体代码如下所示:

//创建intent
Intent resultIntent = new Intent(this, TestActivity.class);
resultIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);           //添加为栈顶Activity
resultIntent.putExtra("what",5);
PendingIntent resultPendingIntent = PendingIntent.getActivity(this,5,resultIntent,PendingIntent.FLAG_UPDATE_CURRENT);
//发送pendingIntent
mBuilder.setContentIntent(resultPendingIntent);
  • 3.5 更新 Notification

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

  • 3.6 取消 Notification

  • 取消通知有如下 5 种方式:

  • 点击通知栏的清除按钮,会清除所有可清除的通知

  • 设置了 setAutoCancel () 或 FLAG_AUTO_CANCEL 的通知,点击该通知时会清除它

  • 通过 NotificationManager 调用 cancel (int id) 方法清除指定 ID 的通知

  • 通过 NotificationManager 调用 cancel (String tag, int id) 方法清除指定 TAG 和 ID 的通知

  • 通过 NotificationManager 调用 cancelAll () 方法清除所有该应用之前发送的通知

  • 注意事项

  • 如果你是通过 NotificationManager.notify (String tag, int id, Notification notify) 方法创建的通知,那么只能通过 NotificationManager.cancel (String tag, int id) 方法才能清除对应的通知,调用 NotificationManager.cancel (int id) 无效。

  • 3.7 设置 flag 属性

  • 设置 FLAG_NO_CLEAR 表示

  • 设置通知不能被状态栏的清除按钮给清除掉,也不能被手动清除,但能通过 cancel () 方法清除

  • 代码:

private void sendNotification9() {
    Notification.Builder mBuilder = new Notification.Builder(this.getApplicationContext())
            .setSound(android.provider.Settings.System.DEFAULT_NOTIFICATION_URI)
            .setSmallIcon(R.mipmap.ic_launcher)                                        //设置通知的图标
            .setTicker("有新消息呢9")                                                    //设置状态栏的标题
            .setContentTitle("这个是标题9")                                              //设置标题
            .setContentText("这个是内容9")                                                //消息内容
            .setDefaults(Notification.DEFAULT_ALL)                                      //设置默认的提示音
            .setOngoing(false)                                                          //让通知左右滑的时候不能取消通知
            .setAutoCancel(true);                                                        //打开程序后图标消失
    Notification notification = mBuilder.build();
    //设置 Notification 的 flags = FLAG_NO_CLEAR
    //FLAG_NO_CLEAR 表示该通知不能被状态栏的清除按钮给清除掉,也不能被手动清除,但能通过 cancel() 方法清除
    //flags 可以通过 |= 运算叠加效果
    notification.flags |= Notification.FLAG_NO_CLEAR;

    //获取NotificationManager 对象
    mNotificationManager.notify(9, notification);
}
//取消通知:
if(mNotificationManager!=null){
    mNotificationManager.cancelAll();
}
  • 3.8 设置 Notification 的通知效果
  • Notification 有震动、响铃、呼吸灯三种响铃效果,可以通过 setDefaults (int defualts) 方法来设置。 Default 属性有以下四种,一旦设置了 Default 效果,自定义的效果就会失效。楼主在这里踩了坑,愣是调了半天没找到为什么自定义效果会消失,忘大家慎之。
//设置系统默认提醒效果,一旦设置默认提醒效果,则自定义的提醒效果会全部失效。具体可看源码//添加默认震动效果,需要申请震动权限//<uses-permission android:name="android.permission.VIBRATE" />
Notification.DEFAULT_VIBRATE
//添加系统默认声音效果,设置此值后,调用setSound()设置自定义声音无效
Notification.DEFAULT_SOUND
//添加默认呼吸灯效果,使用时须与 Notification.FLAG_SHOW_LIGHTS 结合使用,否则无效
Notification.DEFAULT_LIGHTS
//添加上述三种默认提醒效果
Notification.DEFAULT_ALL
  • 除了以上几种设置 Notification 默认通知效果,还可以通过以下几种 FLAG 设置通知效果。
//提醒效果常用 Flag//三色灯提醒,在使用三色灯提醒时候必须加该标志符
Notification.FLAG_SHOW_LIGHTS
//发起正在运行事件(活动中)
Notification.FLAG_ONGOING_EVENT
//让声音、振动无限循环,直到用户响应 (取消或者打开)
Notification.FLAG_INSISTENT
//发起Notification后,铃声和震动均只执行一次
Notification.FLAG_ONLY_ALERT_ONCE
//用户单击通知后自动消失
Notification.FLAG_AUTO_CANCEL
//只有调用NotificationManager.cancel()时才会清除
Notification.FLAG_NO_CLEAR
//表示正在运行的服务
Notification.FLAG_FOREGROUND_SERVICE
  • 设置默认提醒
// 添加默认声音提醒
builder.setDefaults(Notification.DEFAULT_SOUND);
// 添加默认呼吸灯提醒,自动添加FLAG_SHOW_LIGHTS
builder.setDefaults(Notification.DEFAULT_LIGHTS);
  • 设置铃声属性,用的很少
private void sendNotification11() {
    Notification.Builder builder = new Notification.Builder(this)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle("我是伴有铃声效果的通知11")
            .setContentText("美妙么?安静听~11")
            //调用系统默认响铃,设置此属性后setSound()会无效
            //.setDefaults(Notification.DEFAULT_SOUND)
            //调用系统多媒体裤内的铃声
            //.setSound(Uri.withAppendedPath(MediaStore.Audio.Media.INTERNAL_CONTENT_URI,"2"));
            //调用自己提供的铃声,位于 /res/values/raw 目录下
            .setSound(Uri.parse("android.resource://com.yc.cn.ycnotification/" + R.raw.hah));
    //另一种设置铃声的方法
    //Notification notify = builder.build();
    //调用系统默认铃声
    //notify.defaults = Notification.DEFAULT_SOUND;
    //调用自己提供的铃声
    //notify.sound = Uri.parse("android.resource://com.yc.cn.ycnotification/"+R.raw.sound);
    //调用系统自带的铃声
    //notify.sound = Uri.withAppendedPath(MediaStore.Audio.Media.INTERNAL_CONTENT_URI,"2");
    //mManager.notify(11,notify);
    mNotificationManager.notify(11, builder.build());
}
  • 设置震动属性
private void sendNotification12() {
    //震动也有两种设置方法,与设置铃声一样,在此不再赘述
    long[] vibrate = new long[]{0, 500, 1000, 1500};
    Notification.Builder builder = new Notification.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);
    mNotificationManager.notify(12, builder.build());
}
  • 3.9 设置自定义 Notification 通知栏布局
  • 代码如下,注意,这里只取部分代码,完整代码可以下载 github 的完整项目:https://github.com/yangchong211/YCNotification
.setContent(getRemoteViews())                                              // 设置通知栏的布局
//创建自定义布局
private RemoteViews getRemoteViews() {
    RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.notification_mobile_play);
    // 设置 点击通知栏的上一首按钮时要执行的意图
    remoteViews.setOnClickPendingIntent(R.id.btn_pre, getActivityPendingIntent(11));
    // 设置 点击通知栏的下一首按钮时要执行的意图
    remoteViews.setOnClickPendingIntent(R.id.btn_next, getActivityPendingIntent(12));
    // 设置 点击通知栏的播放暂停按钮时要执行的意图
    remoteViews.setOnClickPendingIntent(R.id.btn_start, getActivityPendingIntent(13));
    // 设置 点击通知栏的根容器时要执行的意图
    remoteViews.setOnClickPendingIntent(R.id.ll_root, getActivityPendingIntent(14));
    remoteViews.setTextViewText(R.id.tv_title, "标题");    // 设置通知栏上标题
    remoteViews.setTextViewText(R.id.tv_artist, "艺术家");  // 设置通知栏上艺术家
    return remoteViews;
}

4.Notification 相关属性说明

  • 4.1 PendingIntent 说明

  • 4.1.1 PendingIntent 基本说明

  • PendingIntent 是一种特殊的 Intent ,字面意思可以解释为延迟的 Intent ,用于在某个事件结束后执行特定的 Action 。从上面带 Action 的通知也能验证这一点,当用户点击通知时,才会执行。

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

  • 4.1.2 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)
  • 4.1.3 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 。
  • 4.2 创建返回栈 PendingIntent
  • 4.2.1 添加返回栈代码 默认情况下,从通知启动一个 Activity,按返回键会回到主屏幕。 但某些时候有按返回键仍然留在当前应用的需求,这就要用到 TaskStackBuilder 了。
Notification.Builder mBuilder = new Notification.Builder(context)
                .setSound(android.provider.Settings.System.DEFAULT_NOTIFICATION_URI)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("广播接受者标题,小杨")
                .setContentText("广播接受者内容,扯犊子")
                .setAutoCancel(true);
Log.i(TAG, "onReceive: intent" + intent.getClass().getName());
Intent resultIntent = new Intent(context, MainActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
//将该Activity添加为栈顶
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager = (NotificationManager)
        context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, mBuilder.build());
  • 4.3 注意要点
  • 如果用户的手机使静音模式,那么设置铃声或者震动效果将会失效

5. 部分源码分析思考

  • 5.1 RemoteView 是什么?

  • 5.1.1 什么是 RemoteView?

  • 为啥 Notification 不会设计成和普通 View 一样的使用方式?理由很简单!状态栏不是单单由你的应用程序管理。状态栏是由 Android 系统管理的。你需要显示 Notification 就必须和系统打交道。必须通过 Notification 服务才能显示你的 Notification. 所以设计成用一个 Notification 实例代表一个 Notification, 然后通过 notificationManager.notify 函数提交给 Notification 服务.

  • 5.1.2 Notification 服务是什么?是一个独立的线程!

  • 又扯出一个问题。跨线程显示 View. 该怎么显示?不是在本应用程序显示 View. 这里就要借用 RemoteView.

  • RemoteView 理解成对一个 View 的封装,然后把 RemoteView 提交给其他线程。其他线程接收到 RemoteView 并且解析里面 View 的信息把它显示出来.

  • 5.1.3 在使用系统自带的 Notification 系统会创建一个默认的 RemoteView!

  • 系统默认使用 R.layout.notification_template_material_base 生产一个 RemoteView. 至于这里的布局是怎么查到的,请看下面源码分析

  • 5.2 查看源码,了解 Notification 如何创建布局

  • 5.2.1 首先看 Notification 中 build 代码

  • 5.2.2 然后看上图中的 createContentView () 方法

  • 5.2.3 然后看上图中的 createContentView () 方法

6. 关于其他

  • 6.1 参考案例 http://blog.csdn.net/i_wait_for_you/article/details/70240035
  • 6.2 更新日志
  • v1.0 写于 2016 年 6 月 18 日
  • v1.1 更新于 17 年 12 月 6 日,重新整理笔记
  • 6.3 关于我的博客
  • 我的个人站点:www.yczbj.org,www.ycbjie.cn
  • github:https://github.com/yangchong211
  • 知乎:https://www.zhihu.com/people/yang-chong-69-24/pins/posts
  • 领英:https://www.linkedin.com/in/chong-yang-049216146/
  • 简书:http://www.jianshu.com/u/b7b2c6ed9284
  • csdn:http://my.csdn.net/m0_37700275
  • 网易博客:http://yangchong211.blog.163.com/
  • 新浪博客:http://blog.sina.com.cn/786041010yc
  • 喜马拉雅听书:http://www.ximalaya.com/zhubo/71989305/
  • 脉脉:yc930211
  • 360 图书馆:http://www.360doc.com/myfiles.aspx
  • 开源中国:https://my.oschina.net/zbj1618/blog
  • 泡在网上的日子:http://www.jcodecraeer.com/member/content_list.php?channelid=1
  • 邮箱:yangchong211@163.com
  • 阿里云博客:https://yq.aliyun.com/users/article?spm=5176.100239.headeruserinfo.3.dT4bcV
  • 博客园:http://www.cnblogs.com/yc211/
  • segmentfault 头条:https://segmentfault.com/u/xiangjianyu/articles

今天关于详解Android中Notification的使用方法android notificationmanager的分享就到这里,希望大家有所收获,若想了解更多关于Android Notification 使用方法详解、android Notification 的一个简单应用(在 Notification 中嵌入一个进度条,并且这个 Notification 点击消失但不会跳转)、Android Notification 的使用、Android Notification 详解等相关知识,可以在本站进行查询。

本文标签: