我使用了较新的NotificationCompat构建器,但我无法收到通知以发出声音 . 它会振动并闪烁光线 . android文档说要设置我已完成的样式:
builder.setStyle(new NotificationCompat.InboxStyle());
但没声音?
完整代码:
NotificationCompat.Builder builder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Notifications Example")
.setContentText("This is a test notification");
Intent notificationIntent = new Intent(this, MenuScreen.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
builder.setAutoCancel(true);
builder.setLights(Color.BLUE, 500, 500);
long[] pattern = {500,500,500,500,500,500,500,500,500};
builder.setVibrate(pattern);
builder.setStyle(new NotificationCompat.InboxStyle());
// Add as notification
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(1, builder.build());
14 回答
我以前的代码遗漏了什么:
只需将您的声音文件放在
Res\raw\siren.mp3
文件夹中,然后使用以下代码:对于自定义声音:
对于默认声音:
对于Custom Vibrate:
对于默认振动:
默认声音的另一种方式
使用可以编码
只需输入以下简单代码:
对于默认声音:
你必须使用RingtoneManager
Code for noficationmanager with alarm ringtone 你也可以设置铃声RingtoneManager.TYPE_RINGTONE
你必须使用建设者 . setSound
你可以做一个功能:
收到通知时调用此函数 .
这里raw是res中的文件夹,通知是raw文件夹中的声音文件 .
第1个将“yourmp3file”.mp3文件放在raw文件夹中(即Res文件夹内)
在您的代码中放置第2 ..
这就是我放在我的onClick(View v)中,因为只有“context() . getPackageName()”不会在那里工作,因为它不会得到任何上下文
在Oreo(Android 8)及以上版本中,应该以这种方式完成自定义声音(通知 Channels ):
在任何地方调用此函数 . 这对我有用
您可以执行以下操作:
您可以在资源之间使用raw名称创建一个包,然后保留您的声音,然后调用它 .
通过下面给出的Notification.builder类实例(构建器),您可以在通知时播放默认声音: