2015-10-20 54 views
0

我有一个服务在每次收到新的GCM消息时显示通知PendingIntent。问题是GCM消息可能是不同的。而如果有许多的通知离开未读,我想不分开,但在团体,如告诉他们:获取看不见的android通知

你有型的3个未读消息的

你有B型的2个未读邮件

你有4个未读消息的类型C

据我所知,为了得到这种效果,我需要访问未读/不可见通知。每当我收到新的通知时,我都可以检查是否存在另一个此类型的未读消息,然后决定是创建新通知还是更新旧通知。

我的问题是:有没有办法看到,哪些通知是看不见的,并得到访问它们

对于任何情况,这是我创建消息的方法;如果参数notificationId为0,则应创建新的通知。其他 - 已更新。

private int sendNotification(String msg, Integer notificationId) { 

    Log.d(TAG, "sending message with text: "+msg); 
    mNotificationManager = (NotificationManager) 
      this.getSystemService(Context.NOTIFICATION_SERVICE); 

    Random random = new Random(); 
    int notification_id = notificationId==0?random.nextInt(9999 - 1000) + 1000:notificationId; 

    RemoteViews remoteViews = new RemoteViews(getPackageName(), 
      R.layout.notification); 

    Intent intent = new Intent(this, MainActivity.class); 
    // Send data to NotificationView Class 
    intent.putExtra("text", msg); 

    PendingIntent pending= PendingIntent.getActivity(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); 

    NotificationCompat.Builder mBuilder = 
      new NotificationCompat.Builder(this) 
    .setSmallIcon(R.drawable.ic_launcher) 
    .setContentTitle("escos") 
    .setStyle(new NotificationCompat.BigTextStyle() 
      .bigText(msg)) 
    .setContentText(msg); 
    mBuilder.setContentIntent(pending); 
    mBuilder.setContent(remoteViews); 

    remoteViews.setTextViewText(R.id.notiftext, msg); 
    remoteViews.setImageViewResource(R.id.notifim, R.drawable.ic_launcher); 

    Notification notification = mBuilder.build(); 
    notification.flags |= Notification.FLAG_AUTO_CANCEL; 
    notification.sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); 
    mNotificationManager.notify(notification_id, notification); 

    return notification_id; 
} 

回答

1
  1. 对于状态栏不同的通知条带(A,B,C等),使用不同的NOTIFICATION_ID用于构建上的您从GCM接收defined typecollapse_key基础通知。

  2. 为了确定未读消息,可以使用在共享偏好的本地变量(计数器)和每个通知的特定类型的到来时(上定义的类型或collapse_key的计)的时间加一。

  3. 然后生成具有该特定NOTIFICATION_ID的通知作为具有特定NOTIFICATION_ID的通知可以相互覆盖。因此,您可以在新通知中覆盖之前带有迭代编号文本的通知。

  4. 只要用户点击任何通知或特定通知,清除通知并重置共享首选项中的(计数器)值。

EDIT1:

NotificationManager nMgr = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 
try { 
     nMgr.cancelAll(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

注:当你点击尤其挂起的意图通知,从您的应用程序生成的,然后在活动中使用此代码删除所有通知发请记得在拨打cancelAll()之前添加Try-Catch,因为cancelAll()可能不支持设备型号,并且会生成

java.lang.SecurityException异常:权限拒绝

错误。

编辑2: 您还可以使用nMgr.cancel(NOTIFICATION_ID);清除特定的通知,通过额外NOTIFICATION_ID传递给特定的意图,并获得额外该活动取消特定的通知。

而且当您点击任何通知时,它将从状态栏中清除,除非您尚未在Notification Builder中设置.setAutoCancel(false)

+0

谢谢你,这实际上是我计划如何做到这一点。但我不知道如何实现4.你的名单。 – user2957954

+0

@ user2957954请参阅'Edit1'。 –

+0

如果通知被清除或点击,如何处理仍然不清楚。 – user2957954