Android 监听Notification 被清除实例代码

前言

 一般非常驻的Notification是可以被用户清除的,如果能监听被清除的事件就可以做一些事情,比如推送重新计数的问题。

 正文

 private final broadcastReceiver mbroadcastReceiver = new broadcastReceiver() {

  @Override
  public void onReceive(Context context,Intent intent) {
   if (intent == null || context == null) {
    return;
   }

   mnotificationmanager.cancel(NOTIFICATION_ID_LIVE);

   String type = intent.getStringExtra(PUSH_TYPE);
   if (PUSH_TYPE_LINK.equals(type)) {
    //mNumLinkes = 0;
   } else if (PUSH_TYPE_LIVE.equals(type)) {
    //mNumLives = 0;
   }
   //这里可以重新计数
  }
 };


 private void sendLiveNotification() {
  Intent intent = new Intent(NOTIFICATION_CLICK_ACTION);

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

  String title = "Push测试";
  mBuilder.setContentTitle(title);
  mBuilder.setTicker(title);
  mBuilder.setContentText("https://233.tv/over140");
  mBuilder.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher));
  mBuilder.setSmallIcon(R.drawable.ic_action_cast);
  mBuilder.setDefaults(Notification.DEFAULT_ALL);
  mBuilder.setWhen(System.currentTimeMillis());
  mBuilder.setContentIntent(PendingIntent.getbroadcast(this,NOTIFICATION_ID_LIVE,intent,0));
  mBuilder.setDeleteIntent(PendingIntent.getbroadcast(this,new Intent(NOTIFICATION_DELETED_ACTION).putExtra(PUSH_TYPE,PUSH_TYPE_LIVE),0));

  mnotificationmanager.notify(NOTIFICATION_ID_LIVE,mBuilder.build());
 }

代码说明

  1、最重要的是setDeleteIntent,这个在API Level 11(Android 3.0) 新增的

  2、注意不要设置setAutoCancel为true,否则监听器接收不到

  3、这里统一了点击通知和消除通知的操作

  4、注意广播在推送前要注册

实际使用中发现还是有一点问题,比如Service被Kill掉了,通知栏点击就会没有反应了,这块还需要再考虑一下,比如把broadcast在AndroidMainfest中监听。

以上就是对Android Notification 事件的资料整理,希望能帮助Android开发的朋友。

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...