我使用通知构建器创建通知,如下所示:
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 操作:
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
}
}
请帮帮我。
答案 0 :(得分:0)
notificationBuilder.setDefaults(0)
答案 1 :(得分:-1)
获取NotificationManager的实例:
NotificationManager notify_manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
保存通知的某处ID并致电
notify_manager.cancel(your_id);
或者您可以删除所有通知:
notify_manager.cancelAll();