Sonido de notificación de Android


152

He usado el nuevo constructor NotificationCompat y no puedo recibir la notificación para hacer un sonido. Vibrará y destellará la luz. La documentación de Android dice que establezca un estilo con el que he hecho:

builder.setStyle(new NotificationCompat.InboxStyle());

Pero no hay sonido?

El código completo:

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

12
builder.setSound (Settings.System.DEFAULT_NOTIFICATION_URI) también debería funcionar
— Zar E Ahmer

Respuestas:


256

Lo que faltaba en mi código anterior:

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

44
Sigue jugando y no se detiene, ¿cómo hago que suene solo una vez? utilizando builder.setOnlyOnce (verdadero); no ayuda
— Salis

es una vez jugar
— blackHawk

2
builder.setOnlyOnce (true) resolvió mi problema en mi caso!
— ElOjcar

155

Simplemente ponga su archivo de sonido en la Res\raw\siren.mp3carpeta, luego use este código:

Para sonido personalizado:

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

Para sonido predeterminado:

notification.defaults |= Notification.DEFAULT_SOUND;

Para vibración personalizada:

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

Para vibración predeterminada:

notification.defaults |= Notification.DEFAULT_VIBRATE;

52

Otra forma para el sonido predeterminado

builder.setDefaults(Notification.DEFAULT_SOUND);

12

USE Codificación de latas

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

10

Simplemente ponga el siguiente código simple:

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

Para sonido predeterminado:

notification.defaults |= Notification.DEFAULT_SOUND;

8

Tienes que usar RingtoneManager

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

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

Código para noficationmanager con tono de llamada de alarma , también puede configurar el tono de llamada RingtoneManager.TYPE_RINGTONE

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

Lo sentimos, no es así como lo hace para el NotificationCompat.Builder más nuevo.
— James MV

La notificación se puede crear con la función NotificationCompat.Builder.build () y está bien tomar el valor de retorno de build () y modificar sus valores antes de pasar a NotificationManager.notify. No tiene mucho sentido, pero está perfectamente bien.
— holgac

6

Tienes que usar el constructor. 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());  

1
Escribiste RingtoneManager.TYPE_RINGTONE dos veces.
— Bernardo Ferrari el

6

Puedes hacer una función:

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

Llame a esta función cuando reciba una notificación.

Aquí raw es la carpeta en res y la notificación es el archivo de sonido en la carpeta raw.


6

En Oreo (Android 8) y superior, debe hacerse para un sonido personalizado de esta manera (canales de notificación):

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

5

Primero, coloque el archivo "yourmp3file" .mp3 en la carpeta sin formato (es decir, dentro de la carpeta Res)

2do en su código puesto ..

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

Esto es lo que puse dentro de mi onClick (View v) como solo "context (). GetPackageName ()" no funcionará desde allí ya que no obtendrá ningún contexto


4

En Android OREO o una versión posterior Después de registrar el canal con el sistema; no puede cambiar la importancia u otros comportamientos de notificación después de esto del mismo canal (antes de desinstalar la aplicación)ingrese la descripción de la imagen aquí

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

La prioridad también importa más aquí Establezca la prioridad de notificación en alta mediante

Importancia del nivel de importancia visible para el usuario (Android 8.0 y superior)

1) Urgente Hace un sonido y aparece como una notificación de aviso -> IMPORTANCE_HIGH
2) Alto Hace un sonido -> IMPORTANCE_DEFAULT
3) Medio Sin sonido -> IMPORTANCE_LOW
4) Bajo Sin sonido y no aparece en la barra de estado -> IMPORTANCE_MIN

mismo funciona en el mismo orden Prioridad (Android 7.1 y versiones anteriores)

1) PRIORITY_HIGH o PRIORITY_MAX

2) PRIORITY_DEFAULT

3) PRIORITY_LOW

4) PRIORITY_MIN


1
" no puede cambiar la importancia u otros comportamientos de notificación después de esto del mismo canal ". Necesario para desinstalar la aplicación para que funcione, esta acción eliminó la información del canal del dispositivo como resultado.
— Ely Dantas


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

llama a esta función donde quieras. esto funcionó para mí


0

por Notification.builder clase instancia (constructor) que se proporciona a continuación, puede reproducir sonido predeterminado en la notificación:

builder.setDefaults(Notification.DEFAULT_SOUND);

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

notificación privada nula () {

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

Es una notificación completa con sonido y vibración.


0

No depende del constructor o la notificación. Use un código personalizado para vibrar.

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){
    }
}

-1

Puedes hacer lo siguiente:

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

Crea un paquete entre sus recursos con el nombre de raw y allí guarda sus sonidos y luego lo llama.


-1

// establecer audio de notificación (Probado hasta android 10)

builder.setDefaults(Notification.DEFAULT_VIBRATE);
//OR 
builder.setDefaults(Notification.DEFAULT_SOUND);
Al usar nuestro sitio, usted reconoce que ha leído y comprende nuestra Política de Cookies y Política de Privacidad.
Licensed under cc by-sa 3.0 with attribution required.