2017-03-07 3 views
1

통지를 취소하려고합니다. 다른 통지가 첫 번째 통지보다 15 초 이내에 보내려는 경우 사용자에게 전송되도록 요청했습니다.표시되기 전에 안드로이드 예약 알림을 취소하십시오.

글로벌 변수 :

내 코드입니다

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

관련 문제