Android 通知声音

我已经使用了新的 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());
241687 次浏览

你必须使用 铃声经理

private static final int MY_NOTIFICATION_ID = 1;
private NotificationManager notificationManager;
private Notification myNotification;


private final String myBlog = "http://niravranpara.blogspot.com/";

具有警报铃声 的通知管理器代码也可以设置铃声

notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri
.parse(myBlog));
PendingIntent pi = PendingIntent.getActivity(MainActivity.this, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification note = new Notification(R.drawable.ic_launcher, "Alarm", System.currentTimeMillis());
note.setLatestEventInfo(getApplicationContext(), "Alarm", "sound" + " (alarm)", pi);
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
if(alarmSound == null){
alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
if(alarmSound == null){
alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
}
}
note.sound = alarmSound;
note.defaults |= Notification.DEFAULT_VIBRATE;
note.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(MY_NOTIFICATION_ID, note);

我之前的代码缺少了什么:

Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
builder.setSound(alarmSound);

你必须使用 builder.SetSound

Intent notificationIntent = new Intent(MainActivity.this, MainActivity.class);


PendingIntent contentIntent = PendingIntent.getActivity(MainActivity.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());
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
if(alarmSound == null){
alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
if(alarmSound == null){
alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
}
}


// Add as notification
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
builder.setSound(alarmSound);
manager.notify(1, builder.build());

只要把你的声音文件放在 Res\raw\siren.mp3文件夹中,然后使用下面的代码:

自定义声音:

Notification notification = builder.build();
notification.sound = Uri.parse("android.resource://"
+ context.getPackageName() + "/" + R.raw.siren);

默认声音:

notification.defaults |= Notification.DEFAULT_SOUND;

自定义振动:

long[] vibrate = { 0, 100, 200, 300 };
notification.vibrate = vibrate;

默认振动:

notification.defaults |= Notification.DEFAULT_VIBRATE;

只需要写下面的简单代码:

notification.sound = Uri.parse("android.resource://"
+ context.getPackageName() + "/" + R.raw.sound_file);

默认声音:

notification.defaults |= Notification.DEFAULT_SOUND;

默认声音的另一种方式

builder.setDefaults(Notification.DEFAULT_SOUND);
notification.sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);

可以编码

 String en_alert, th_alert, en_title, th_title, id;
int noti_all, noti_1, noti_2, noti_3, noti_4 = 0, Langage;


class method
Intent intent = new Intent(context, ReserveStatusActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);


NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);




intent = new Intent(String.valueOf(PushActivity.class));
intent.putExtra("message", MESSAGE);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(PushActivity.class);
stackBuilder.addNextIntent(intent);
// PendingIntent pendingIntent =
stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);


//      android.support.v4.app.NotificationCompat.BigTextStyle bigStyle = new NotificationCompat.BigTextStyle();
//        bigStyle.bigText((CharSequence) context);






notification = new NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(th_title)
.setContentText(th_alert)
.setAutoCancel(true)


// .setStyle(new Notification.BigTextStyle().bigText(th_alert)  ตัวเก่า
//


.setStyle(new NotificationCompat.BigTextStyle().bigText(th_title))


.setStyle(new NotificationCompat.BigTextStyle().bigText(th_alert))


.setContentIntent(pendingIntent)
.setNumber(++numMessages)




.build();


notification.sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);


notificationManager.notify(1000, notification);

首先将“ yourmp3file”. mp3文件放入原始文件夹(即 Res 文件夹内)

在你的代码第二把. 。

Notification noti = new Notification.Builder(this)
.setSound(Uri.parse("android.resource://" + v.getContext().getPackageName() + "/" + R.raw.yourmp3file))//*see note

这是我在 onClick (View v)中仅仅作为“ context ()”放入的内容。GetPackageName ()”不能从那里工作,因为它不能获得任何上下文

你可以做一个函数:

public void playNotificationSound()
{
try
{


Uri alarmSound = `Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + MyApplication.getInstance().getApplicationContext().getPackageName() + "/raw/notification");`
Ringtone r = RingtoneManager.getRingtone(MyApplication.getInstance().getApplicationContext(), alarmSound);
r.play();
}
catch (Exception e)
{
e.printStackTrace();
}
}

收到通知时调用此函数。

这里原始文件夹在 res 和通知是原始文件夹中的声音文件。

你可以这样做:

MediaPlayer mp;
mp =MediaPlayer.create(Activity_Order_Visor_Atender.this, R.raw.ok);
mp.start();

你在你的资源之间创建了一个带有原始名称的包,在那里你保留了你的声音,然后你就可以调用它。

通过下面给出的 Notification.Builder 类实例(Builder) ,你可以在通知时播放默认声音:

builder.setDefaults(Notification.DEFAULT_SOUND);

在奥利奥(Android 8)及以上版本中,应该以这种方式(通知频道)定制声音:

Uri soundUri = Uri.parse(
"android.resource://" +
getApplicationContext().getPackageName() +
"/" +
R.raw.push_sound_file);


AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_ALARM)
.build();


// Creating Channel
NotificationChannel channel = new NotificationChannel("YOUR_CHANNEL_ID",
"YOUR_CHANNEL_NAME",
NotificationManager.IMPORTANCE_HIGH);
channel.setSound(soundUri, audioAttributes);


((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE))
.createNotificationChannel(notificationChannel);
private void showNotification() {


// intent triggered, you can add other intent for other actions
Intent i = new Intent(this, MainActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, i, 0);


//Notification sound
try {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
} catch (Exception e) {
e.printStackTrace();
}


// this is it, we'll build the notification!
// in the addAction method, if you don't want any icon, just set the first param to 0
Notification mNotification = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {


mNotification = new Notification.Builder(this)


.setContentTitle("Wings-Traccar!")
.setContentText("You are punched-in for more than 10hrs!")
.setSmallIcon(R.drawable.wingslogo)
.setContentIntent(pIntent)
.setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 })
.addAction(R.drawable.favicon, "Goto App", pIntent)
.build();


}


NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);


// If you want to hide the notification after it was selected, do the code below
// myNotification.flags |= Notification.FLAG_AUTO_CANCEL;


notificationManager.notify(0, mNotification);
}

随便调用这个函数,我就是这么做的

在 Android < strong > OREO 或更高版本中 enter image description here 向系统注册信道后; 你不能改变重要性 或者 其他通知行为之后,这相同的通道 (卸载应用程序前)

private void createNotificationChannel() {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = getString(R.string.channel_name);
String description = getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.setDescription(description);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}


channel.setSound(Settings.System.DEFAULT_NOTIFICATION_URI,audioAttributes);

在这里,优先权也是最重要的 设置 Notification高度优先

用户可见的重要性级别重要性(Android 8.0及更高版本)

发出声音并显示为提示通知-> < strong > IMPORTANCE _ HIGH
2)高 发出声音-> < strong > IMPORTANCE _ DEFAULT
3)中等 无声-> 重要性 _ 低
4) Low 无声音且不出现在状态栏-> < strong > IMPORTANCE _ MIN

同样的作品按同样的顺序 优先级(Android 7.1及以下版本)

1)优先级 _ 高或优先级 _ 最大

2)优先级 _ 缺省值

3)优先级低

4)优先级 _ 最小

//设置通知音频(测试至 android 10)

builder.setDefaults(Notification.DEFAULT_VIBRATE);
//OR
builder.setDefaults(Notification.DEFAULT_SOUND);
Button btn;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user);


btn= findViewById(R.id.btn);


btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
notification();
}
});
}






private void notification() {
NotificationCompat.Builder builder= new
NotificationCompat.Builder(this);
builder.setAutoCancel(true);
builder.setContentTitle("Work Progress");
builder.setContentText("Submit your today's work progress");
builder.setSmallIcon(R.drawable.ic_email_black_24dp);
Intent intent=new Intent(this, WorkStatus.class);
PendingIntent pendingIntent= PendingIntent.getActivity(this, 1, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pendingIntent);
builder.setDefaults(Notification.DEFAULT_VIBRATE);
builder.setDefaults(Notification.DEFAULT_SOUND);


NotificationManager notificationManager= (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(1, builder.build());
}

它是完全通知与声音和振动

不要依赖于建设者或通知。振动使用自定义代码。

public static void vibrate(Context context, int millis){
try {
Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
v.vibrate(VibrationEffect.createOneShot(millis, VibrationEffect.DEFAULT_AMPLITUDE));
} else {
v.vibrate(millis);
}
}catch(Exception ex){
}
}

有几个答案讨论了 NotificationChannel.setSound ()对于 Oreo (Android 8,api 26)及以上版本的使用,并且一旦创建了一个通道,就不能更改它。

我没有意识到的是,当 AndroidStudio 运行您的应用程序并执行“安装”步骤时,它会显示 先卸载以前的版本及其 NotificationChannel。因此,更改某些内容(例如声音)和简单地重新运行将不会起作用。你需要先卸载 明确地应用程序,然后再运行它。

这是声线

notification.setDefaults(Notification.DEFAULT_SOUND)

例子

private fun createNotification()  {
val downloadLogo = BitmapFactory.decodeResource(applicationContext.resources, R.drawable.download)
val notificationManager = createNotificationChannel()
val notification = NotificationCompat.Builder(applicationContext, "CHANNEL_ID")
.setSmallIcon(R.drawable.download)
.setContentTitle("Download")
.setContentText("Download Successfully")
.setLargeIcon(downloadLogo)


notification.setDefaults(Notification.DEFAULT_SOUND)
notificationManager.notify(0, notification.build())
}




private fun createNotificationChannel():NotificationManager {
val notificationManager = applicationContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val name = applicationContext.getString(R.string.channel_name)
val descriptionText = applicationContext.getString(R.string.channel_description)
val importance = NotificationManager.IMPORTANCE_DEFAULT
val channel = NotificationChannel("CHANNEL_ID", name, importance).apply {
description = descriptionText
}
notificationManager.createNotificationChannel(channel)
}
return notificationManager
}