2017-03-07 10 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); 

通知が掲載されるまではnullのままNMので、この方法のdoesn通知は作成した後で、通知を削除する方法と、通知が.notifyによって通知される前に行う必要があります。

ありがとうございました。

+0

完全な例を示してください。クラス宣言とメソッド宣言を含める必要があります。 –

+0

alarmManager.cancel(pendingIntent)を呼び出すことができます。もっと読む:http://stackoverflow.com/questions/30075196/how-can-i-cancel-unshown-notifications-in-android –

答えて

1

理想的には、このようなものに対して変数のヌル状態に頼りたくはありません。
代わりに、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

関連する問題