Android Notification 事件 Android 监听Notification 被清除实例代码

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Android Notification 事件 Android 监听Notification 被清除实例代码

  2021-03-22 我要评论
想了解Android 监听Notification 被清除实例代码的相关内容吗,在本文为您仔细讲解Android Notification 事件的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Android,Notification,事件,Android,Notification,详解,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, NOTIFICATION_ID_LIVE, 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开发的朋友。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们