Descubrí que estoy usando un método obsoleto para noficitaciones (notification.setLatestEventInfo ())
Dice usar Notification.Builder.
- ¿Como lo uso?
Cuando intento crear una nueva instancia, me dice:
Notification.Builder cannot be resolved to a type
Descubrí que estoy usando un método obsoleto para noficitaciones (notification.setLatestEventInfo ())
Dice usar Notification.Builder.
Cuando intento crear una nueva instancia, me dice:
Notification.Builder cannot be resolved to a type
Respuestas:
Esto está en API 11, por lo que si está desarrollando para algo anterior a 3.0, debe continuar usando la API anterior.
Actualización : la clase NotificationCompat.Builder se ha agregado al paquete de soporte para que podamos usar 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);
Notification.Builderpágina de documentos. Estaba haciendo lo que decían, pero no tenía ningún sentido. Vengo aquí y veo que es diferente. Realmente aprecio tu respuesta, ya que me hizo consciente del error que está en el documento.
builder.getNotification()está en desuso. Dice que debes usar builder.build().
setSmallIcon(), setContentTitle()y setContentText()son los requisitos mínimos.
Además de la respuesta seleccionada, aquí hay un código de muestra para la NotificationCompat.Builderclase de Source Tricks :
// 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 el nivel de API de Android 11 y superior (Android 3.0 y superior).
Por lo tanto, si no está apuntando a tabletas Honeycomb, no debe usar el Generador de notificaciones, sino seguir métodos de creación de notificaciones más antiguos, como el siguiente ejemplo .
Visite el enlace de actualizaciones de notificaciones para obtener más detalles.
Android N también te permite agrupar notificaciones similares para que aparezcan como una sola notificación. Para que esto sea posible, Android N utiliza el
NotificationCompat.Builder.setGroup()método . Los usuarios pueden expandir cada una de las notificaciones y realizar acciones como responder y descartar en cada una de las notificaciones, individualmente desde el tono de notificación.Esta es una muestra preexistente que muestra un servicio simple que envía notificaciones usando NotificationCompat. Cada conversación no leída de un usuario se envía como una notificación distinta.
Esta muestra se ha actualizado para aprovechar las nuevas funciones de notificación disponibles en Android N.
Estaba teniendo problemas para crear notificaciones (solo 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. Solo como base para la resolución de problemas con esto, asegúrese de tener todos estos como mínimo. Con suerte, esto le evitará un dolor de cabeza a otra persona.
En caso de que ayude a alguien ... Estaba teniendo muchos problemas para configurar notificaciones usando el paquete de soporte cuando probaba con una API más nueva y antigua. Pude hacer que funcionaran en el dispositivo más nuevo, pero obtendría una prueba de error en el dispositivo anterior. Lo que finalmente hizo que funcionara para mí fue eliminar todas las importaciones relacionadas con las funciones de notificación. En particular, NotificationCompat y TaskStackBuilder. Parece que mientras configuraba mi código al principio, las importaciones se agregaron desde la compilación más nueva y no desde el paquete de soporte. Luego, cuando quise implementar estos elementos más adelante en eclipse, no se me pidió que los volviera a importar. Espero que tenga sentido y que ayude a alguien más :)
Funciona incluso en API 8, puedes usar 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.
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());
// 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
Misma técnica que en esta respuesta pero:
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.