在Android中2小时后自动取消/删除推送通知

时间:2015-01-03 15:36:17

标签: android push-notification

我有一个要求,即如果没有查看2小时,收到的GCM推送通知应自动取消/销毁。该应用可能或可能不在后台。提供服务是解决这个问题的最佳方式吗?还有其他任何建议吗?

3 个答案:

答案 0 :(得分:0)

Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
              String ns = Context.NOTIFICATION_SERVICE;
            NotificationManager nMgr = (NotificationManager) getApplicationContext().getSystemService(ns);
            nMgr.cancel(NOTIF_ID);
        }
    }, 600000);

答案 1 :(得分:0)

是.Service是可靠更新的最佳解决方案,也适用于后台。

1.保留本地临时表(DTO),保存所有收到的通知,并添加字段通知到达时间。

2.在服务类别中与当前时间和通知时间进行比较,如果超过2小时,则从表格中删除通知项目并取消通知。

这是代码

public class Notyficationclr extends Service {

@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public void onCreate() {
    super.onCreate();
  for(Notification not:NotifcationTable.getAll()){

      if(IntervalOver(not)){
         //Code for delete Notification from table
         //code for cancel notification 
       }


}




public boolean IntervalOver(Notification notification) {
        boolean istimeout = false;
        SimpleDateFormat sdf = new SimpleDateFormat("EE MMM dd HH:mm:ss z yyyy");
        SimpleDateFormat hformat = new SimpleDateFormat("HH");
        SimpleDateFormat mformat = new SimpleDateFormat("mm");
        String hour = null, min = null;
        Date arrivatedatetime = null;

        try {
            arrivatedatetime = sdf.parse(notification.getArrivalTime());
        } catch (java.text.ParseException e) {          
            e.printStackTrace();
        }


        Date currentDate = new Date(System.currentTimeMillis());
        long diff = currentDate.getTime() - arrivatedatetime.getTime();

        long seconds = diff / 1000;
        long minutes = seconds / 60;
        long hours = minutes / 60;
        long days = hours / 24;


            if (hours >=2) {
                istimeout = true;
            }

        return istimeout;
}

答案 2 :(得分:0)

对于那些寻找简单答案的人,现在可以使用 Notification.Builder 中的 setTimeOutAfter 轻松完成。

以下是 Google 文档中有关如何使用它的 API 详细信息。 Link