Cómo utilizar exactamente Notification.Builder
Encontré que estoy usando un método obsoleto para nofictions (notification.setLatestEventInfo ())
Dice usar Notification.Builder.
- Programo una notificación local en un momento específico, utilizando el conmutador, pero su activación no a tiempo establecido
- ¿Puedo anular el icono predeterminado de notificación push en android desde el icono de la aplicación hasta el icono personalizado?
- Notificaciones de Toast que no aparecen en Nexus 7 Tablet
- Android: ¿Cómo puedo poner mi notificación encima del área de notificación?
- Clic de notificación: actividad ya abierta
- ¿Como lo uso?
Cuando intento crear una nueva instancia, me dice:
Notification.Builder cannot be resolved to a type
- ¿Cómo obtener un notificador de aplicación PERMANENTE en la barra de estado?
- Cómo quitar la notificación de la barra de notificación mediante programación en android?
- Azure push notificación hub - cómo manejar los formatos de carga útil para iOS y Android?
- Android Parse, notificaciones y buildTypes
- Cómo dar contador si hay más de una notificación
- Acciones de notificaciones de Android sin abrir la aplicación
- Notificación de Android BigPictureStyle desaparición de texto
- RemoteView no muestra botones en la notificación personalizada
Esto está en la API 11, por lo que si está desarrollando algo anterior a 3.0 debe seguir utilizando la API antigua.
Actualización : la clase NotificationCompat.Builder se ha agregado al paquete de soporte para que podamos utilizar esto para admitir el nivel de API v4 y superior:
http://developer.android.com/reference/android/support/v4/app/NotificationCompat.Builder.html
Notification.Builder API 11 o NotificationCompat.Builder API 1
Este es un ejemplo de uso.
Intent notificationIntent = new Intent(ctx, YourClass.class); PendingIntent contentIntent = PendingIntent.getActivity(ctx, YOUR_PI_REQ_CODE, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT); NotificationManager nm = (NotificationManager) ctx .getSystemService(Context.NOTIFICATION_SERVICE); Resources res = ctx.getResources(); Notification.Builder builder = new Notification.Builder(ctx); builder.setContentIntent(contentIntent) .setSmallIcon(R.drawable.some_img) .setLargeIcon(BitmapFactory.decodeResource(res, R.drawable.some_big_img)) .setTicker(res.getString(R.string.your_ticker)) .setWhen(System.currentTimeMillis()) .setAutoCancel(true) .setContentTitle(res.getString(R.string.your_notif_title)) .setContentText(res.getString(R.string.your_notif_text)); Notification n = builder.build(); nm.notify(YOUR_NOTIF_ID, n);
Además de la respuesta seleccionada aquí hay algún código de ejemplo para la clase NotificationCompat.Builder
de Trucos de origen :
// Add app running notification private void addNotification() { 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, MainActivity.class); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); builder.setContentIntent(contentIntent); // Add as notification NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); manager.notify(FM_NOTIFICATION_ID, builder.build()); } // Remove notification private void removeNotification() { NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); manager.cancel(FM_NOTIFICATION_ID); }
Notification Builder es estrictamente para Android API Nivel 11 y superior (Android 3.0 y versiones posteriores).
Por lo tanto, si no está apuntando a las tabletas Honeycomb, no debería utilizar el Generador de notificaciones, sino seguir métodos de creación de notificaciones más antiguos como el ejemplo siguiente.
Tenía un problema al crear notificaciones (solo en desarrollo para Android 4.0+). Este enlace me mostró exactamente lo que estaba haciendo mal y dice lo siguiente:
Required notification contents A Notification object must contain the following: A small icon, set by setSmallIcon() A title, set by setContentTitle() Detail text, set by setContentText()
Básicamente me faltaba uno de estos. Así como una base para la solución de problemas con esto, asegúrese de tener todos estos, por lo menos. Espero que esto le ahorrará a alguien más un dolor de cabeza.
ACTUALIZACIÓN android-N (marzo-2016)
Visite el enlace Actualizaciones de notificaciones para obtener más detalles.
- Respuesta Directa
- Notificaciones incluidas
- Vistas personalizadas
Android N también le permite agrupar notificaciones similares para que aparezcan como una sola notificación. Para que esto sea posible, Android N utiliza el método
NotificationCompat.Builder.setGroup()
existente. Los usuarios pueden expandir cada una de las notificaciones y realizar acciones como responder y rechazar cada una de las notificaciones, individualmente desde la pantalla de notificación.Este es un ejemplo preexistente que muestra un servicio sencillo que envía notificaciones mediante NotificationCompat. Cada conversación no leída de un usuario se envía como una notificación distinta.
Este ejemplo se ha actualizado para aprovechar las nuevas funciones de notificación disponibles en Android N.
Código de ejemplo .
En caso de que ayuda a alguien … Tenía un montón de problemas con la configuración de notificaciones mediante el paquete de soporte técnico cuando se prueba contra una nueva API más antigua. Pude conseguir que funcionaran en el dispositivo más nuevo pero conseguiría una prueba de error en el viejo dispositivo. Lo que finalmente consiguió que funcione para mí fue eliminar todas las importaciones relacionadas con las funciones de notificación. En particular el NotificationCompat y el TaskStackBuilder. Parece que mientras que la configuración de mi código en el principio de las importaciones se agregó de la nueva generación y no desde el paquete de soporte. Luego, cuando quería implementar estos elementos más tarde en eclipse, no se me pidió que los importara de nuevo. Espero que tenga sentido, y que ayude a alguien a salir 🙂
Funciona incluso en API 8 puede utilizar este código:
Notification n = new Notification(R.drawable.yourownpicturehere, getString(R.string.noticeMe), System.currentTimeMillis()); PendingIntent i=PendingIntent.getActivity(this, 0, new Intent(this, NotifyActivity.class), 0); n.setLatestEventInfo(getApplicationContext(), getString(R.string.title), getString(R.string.message), i); n.number=++count; n.flags |= Notification.FLAG_AUTO_CANCEL; n.flags |= Notification.DEFAULT_SOUND; n.flags |= Notification.DEFAULT_VIBRATE; n.ledARGB = 0xff0000ff; n.flags |= Notification.FLAG_SHOW_LIGHTS; // Now invoke the Notification Service String notifService = Context.NOTIFICATION_SERVICE; NotificationManager mgr = (NotificationManager) getSystemService(notifService); mgr.notify(NOTIFICATION_ID, n);
O sugiero seguir un excelente tutorial sobre esto
Veo que esto funciona desde el nivel 11 de la API (Android 3.0).
// This is a working Notification private static final int NotificID=01; b= (Button) findViewById(R.id.btn); b.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Notification notification=new Notification.Builder(MainActivity.this) .setContentTitle("Notification Title") .setContentText("Notification Description") .setSmallIcon(R.mipmap.ic_launcher) .build(); NotificationManager notificationManager=(NotificationManager)getSystemService(NOTIFICATION_SERVICE); notification.flags |=Notification.FLAG_AUTO_CANCEL; notificationManager.notify(NotificID,notification); } }); }
Ejemplo autónomo
La misma técnica que en esta respuesta pero:
- Autónomo: copiar y copiar y compilar y ejecutar
- Con un botón para que generas tantas notificaciones como quieras y juegues con ID de intenciones y notificaciones
Fuente:
import android.app.Activity; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.view.View; import android.widget.Button; public class Main extends Activity { private int i; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Button button = new Button(this); button.setText("click me"); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final Notification notification = new Notification.Builder(Main.this) /* Make app open when you click on the notification. */ .setContentIntent(PendingIntent.getActivity( Main.this, Main.this.i, new Intent(Main.this, Main.class), PendingIntent.FLAG_CANCEL_CURRENT)) .setContentTitle("title") .setAutoCancel(true) .setContentText(String.format("id = %d", Main.this.i)) // Starting on Android 5, only the alpha channel of the image matters. // https://stackoverflow.com/a/35278871/895245 // `android.R.drawable` resources all seem suitable. .setSmallIcon(android.R.drawable.star_on) // Color of the background on which the alpha image wil drawn white. .setColor(Color.RED) .build(); final NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(Main.this.i, notification); // If the same ID were used twice, the second notification would replace the first one. //notificationManager.notify(0, notification); Main.this.i++; } }); this.setContentView(button); } }
Probado en Android 22.
He usado
Intent intent = new Intent(this, MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT); Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.mipmap.ic_launcher) .setContentTitle("Firebase Push Notification") .setContentText(messageBody) .setAutoCancel(true) .setSound(defaultSoundUri) .setContentIntent(pendingIntent); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(0, notificationBuilder.build());
- Android – Pulling SQlite base de datos dispositivo Android
- SQLite en Android Cómo actualizar una fila específica