Android通知播放声音一次
问题描述:
我使用发送通知该代码将用户:Android通知播放声音一次
NotificationManager notificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
Group group = new Group(Integer.parseInt(serverNotification.getGroupID()), serverNotification.getGroupTitle());
Intent intent = new Intent(this, MainActivity.class);
if (serverNotification.getType() != Notification.NotificationType.VIDEO_PROCESS_COMPLETED) {
intent.putExtra(MainActivity.EXTRA_MODE, MainActivity.MODE_GROUP_VIDEOS);
intent.putExtra(MainActivity.EXTRA_GROUP, group);
if (serverNotification.getVideoID() != null && serverNotification.getVideoID().length() != 0) {
intent.putExtra(MainActivity.EXTRA_VIDEO_ID, serverNotification.getVideoID());
}
}
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
android.app.Notification.Builder builder = new android.app.Notification.Builder(this)
.setSmallIcon(R.drawable.notification_icon)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher))
.setWhen(System.currentTimeMillis())
.setContentText(serverNotification.getMessage())
.setTicker(serverNotification.getMessage())
.setAutoCancel(true)
.setContentTitle("MyApp");
builder.setContentIntent(contentIntent);
if (Build.VERSION.SDK_INT >= 16) {
notificationManager.notify(GROUP_NOTIFICATION_ID++, builder.build());
} else {
notificationManager.notify(GROUP_NOTIFICATION_ID++, builder.getNotification());
}
try {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
} catch (Exception e) {
e.printStackTrace();
}
的问题是,当我得到(连续3+)多个通知它播放声音多次,有是只有一次播放声音的方法吗?
答
你并不需要自己播放的声音 - 尝试:
builder.setSound( RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
甚至更好,因为你使用的是默认的声音: builder.setDefaults(Notification.DEFAULT_SOUND);
而刚刚通过的方式 - 避免在代码中使用显式数字(和文字),请使用常量: Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN
而不是Build.VERSION.SDK_INT < 16
。它确实提高了代码的可读性。