Search code examples
androidandroid-notifications

How to stop playing notification sound programmatically on Android


I create notification using notification builder like this:

NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
String someString = "StackOverflow is the best";
builder.setContentTitle(someString)
            .setContentIntent(contentIntent)
            .setLights(0xFF00FF00, 500, 3000)
            .setPriority(Notification.PRIORITY_MAX)
            .setAutoCancel(true);
Notification notif = builder.build();
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
if (Build.VERSION.SDK_INT >= 21) {
      notif.sound = soundUri;
      AudioAttributes.Builder attrs = new AudioAttributes.Builder();
      attrs.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION);
      attrs.setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE);
      notif.audioAttributes = attrs.build();
} else {
      builder.setSound(soundUri, AudioManager.STREAM_RING);
      notif = builder.build();
}

notif.flags = notif.flags & (~ Notification.FLAG_INSISTENT);
return notif;

Problem is that I can't stop playing sound, until opening Notification Panel. I need to stop this sound with click on power button. I created service, that detects android.intent.action.SCREEN_ON and android.intent.action.SCREEN_OFF actions:

public class StopNotificationSoundService extends Service {
  private BroadcastReceiver sReceiver;

  public IBinder onBind(Intent arg) {
      return null;
  }

  public int onStartCommand(Intent intent, int flag, int startIs) {
      IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
      filter.addAction(Intent.ACTION_SCREEN_OFF);
      sReceiver = new StopSoundNotificationReceiver();
      registerReceiver(sReceiver, filter);
      return START_STICKY;
  }

  public void onDestroy() {
      if (sReceiver != null)
          unregisterReceiver(sReceiver);
      super.onDestroy();
  }

}

And here is broadcast receiver:

    public class StopSoundNotificationReceiver extends BroadcastReceiver {
      @Override
      public void onReceive(Context context, Intent intent) {
          Log.d("LOG_TAG", "StopSoundNotificationReceiver");
          // Here is code that stops sound
      }
  }

Help me with this, please.


Solution

  • Grab instance of NotificationManager:

        NotificationManager notify_manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    

    Save somewhere ID of your notification and call

        notify_manager.cancel(your_id);
    

    Or you can remove all notifications:

        notify_manager.cancelAll();