2017-03-07 40 views
1

我試圖取消通知我已經請求發送給用戶,如果另一個通知嘗試在第一個通知的15秒內發送。在顯示android取消安排的通知之前

這是我的代碼:

全局變量:

public NotificationManager nm; 

通知功能:

final NotificationCompat.Builder b = new NotificationCompat.Builder(this); 

    b.setAutoCancel(true) 
      .setDefaults(NotificationCompat.DEFAULT_ALL) 
      .setSmallIcon(R.mipmap.ic_launcher) 
      .setLargeIcon(BitmapFactory.decodeResource(getResources(), 
        R.mipmap.ic_launcher)) 
      .setContentTitle(title) 
      .setContentText(message); 

    if (nm != null) { 
     Log.d(TAG, "notifyThis: cancelled"); 
     nm.cancelAll(); 
    } else { 
     Log.d(TAG, "notifyThis: not cancelled"); 
    } 

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

    new Handler().postDelayed(new Runnable() { 
     @Override 
     public void run() { 

      nm.notify(1, b.build()); 
      Log.d(TAG, "notifyThis: notify"); 

     } 
    }, 15000); 

我注意到,直到通知發佈納米保持空,因此這個方法沒有按不起作用,但我需要一種方式在創建通知之後以及在通過.notify發佈之前刪除通知。

感謝。

+0

請顯示完整的示例。你應該包括類和方法聲明。 –

+0

您可以調用alarmManager.cancel(pendingIntent);閱讀更多在這裏:http://stackoverflow.com/questions/30075196/how-can-i-cancel-unshown-notifications-in-android –

回答

1

理想情況下,你不想依賴變量的null狀態來實現這樣的事情。
而是,Handler類具有刪除先前計劃的任務的方法。爲此,您需要保持對Handler和Runnable對象的引用。

private Handler handler = new Handler(); 
private boolean isPosted = false; 
private Runnable notificationRunnable; 

void doNotification() { 
    final NotificationCompat.Builder b = {...} 

    if(isPosted) { 
     handler.removeCallbacks(notificationRunnable); 
     isPosted = false; 
    } 
    else { 
     notificationRunnable = new Runnable() { 
      @Override 
      public void run() { 
       nm.notify(1, b.build()); 
       Log.d(TAG, "notifyThis: notify"); 
      } 
     }; 
     handler.postDelayed(notificationRunnable, 15000); 
     isPosted = true; 
    } 
} 
+0

這個答案是偉大的,但唯一的問題是,我失去了我的對象的引用爲這個函數在一個IntentService類中(我忘了提到),所以每當它被調用時它就創建一個新的對象引用。有沒有什麼辦法保持對IntentService中的對象的引用? – Haris

+0

忘了標籤@RobCo – Haris