如何在Android上以编程方式停止播放通知声音 [英] How to stop playing notification sound programmatically on Android

查看:173
本文介绍了如何在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;

问题是我无法停止播放声音,直到打开通知面板.我需要通过单击电源按钮停止此声音.我创建了服务,该服务可检测 android.intent.action.SCREEN_ON android.intent.action.SCREEN_OFF 动作:

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();
  }

}

这是广播接收器:

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

请帮助我.

推荐答案

NotificationManager的抢占实例:

Grab instance of NotificationManager:

    NotificationManager notify_manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

将通知的ID保存在某处并致电

Save somewhere ID of your notification and call

    notify_manager.cancel(your_id);

或者您可以删除所有通知:

Or you can remove all notifications:

    notify_manager.cancelAll();

这篇关于如何在Android上以编程方式停止播放通知声音的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆