2011-10-23 14 views
6

Tengo una clase que amplía BroadcastReceiver que se llama cada vez que hay nuevos resultados de exploración Wifi (el receptor está registrado en el manifiesto con la transmisión Scan_Results como filtro de intención).Notificación de presentación de Android de BroadcastReceiver

De esta clase, quiero poder mostrar una notificación al usuario. Actualmente, transfiero el contexto que se recibe como parámetro en el método onReceive de mi clase de intención de difusión a un método de "mostrar notificación" de otra clase.

Cuando se llega a la línea:

myNotificationManager.notify(notificationId, notification); 

falla con la siguiente excepción:

java.lang.IllegalArgumentException: contentView required: pkg=com.mumfordmedia.trackify id=2131034122 notification=Notification(vibrate=null,sound=null,defaults=0x0,flags=0x0) 

Alguna idea de por qué ocurre esto? Todo lo que puedo pensar es porque el contexto que obtengo del parámetro onReceive no es ... a falta de una frase mejor, "correcto para el trabajo" ...

¿Alguna idea? Gracias, Max.

+1

Tal vez esto http://stackoverflow.com/questions/2826786/pendingintents-in-notifications ayudará. De todos modos, muéstranos más código para que podamos ayudarte. – Jong

+2

Por favor muéstranos un poco más de tu código para que podamos tener una mejor idea de lo que está pasando. –

+0

Por cierto, ¡Bienvenido a Stackoverflow! Si una respuesta es útil, dele un voto. Si la respuesta responde con éxito a su pregunta, haga clic en la marca de verificación verde al lado para aceptar la respuesta. –

Respuesta

0

Por lo que puedo decir, cuando está creando una notificación para pasar al Administrador de notificaciones, no le está dando una vista de contenido para mostrar. Revise la línea donde realmente crea la notificación para ver si realmente está dando a la notificación una vista para mostrar.

+0

Copié y pegué el script de notificación desde otro lugar de la aplicación donde funciona.No hay vista de contenido disponible porque se está activando desde una clase que amplía un BroadcastReceiver que no tiene ningún diseño. ¿Por qué necesita una vista de contenido? Voy a revisar la documentación en unas horas ... gracias por la respuesta por cierto –

2

No estoy seguro exactamente por qué no estaba trabajando antes, pero aquí está el código que tengo trabajo con:

declaramos lo siguiente fuera de cualquier método:

int YOURAPP_NOTIFICATION_ID = 1234567890; 
NotificationManager mNotificationManager; 

Luego, en el método OnReceive llamar al siguiente :

mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); 
showNotification(context, R.drawable.icon, "short", false); 

Entonces Declarar el método siguiente:

private void showNotification(Context context, int statusBarIconID, String string, boolean showIconOnly) { 
     // This is who should be launched if the user selects our notification. 
     Intent contentIntent = new Intent(); 

     // choose the ticker text 
     String tickerText = "ticket text"; 

     Notification n = new Notification(R.drawable.icon, "ticker text", System.currentTimeMillis()); 

     PendingIntent appIntent = PendingIntent.getActivity(context, 0, contentIntent, 0); 

     n.setLatestEventInfo(context, "1", "2", appIntent); 

     mNotificationManager.notify(YOURAPP_NOTIFICATION_ID, n); 
    } 
+0

este código se ejecuta para mí. gracias :) – IRvanFauziE

2

Tiene que llamar a Notification.setLatestEventInfo().

1

Use este código junto con la notificación

Intent intent = new Intent(this, MusicDroid.class); 
PendingIntent activity = PendingIntent.getActivity(this, 0, intent, 0); 
notification.setLatestEventInfo(this, "This is the title", 
    "This is the text", activity); 
notification.number += 1; 

nm.notify(NOTIFY_ID, notification); 
14

ContentView es la vista que se requiere cuando se hace clic en la notificación. El código siguiente funciona bien y setLatestEventInfo() es un método obligatorio.

NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 
    Notification notification = new Notification(R.drawable.ic_launcher, 
      "Hello from service", System.currentTimeMillis()); 
    Intent intent = new Intent(this, MainActivity.class); 
    notification.setLatestEventInfo(this, "contentTitle", "contentText", 
      PendingIntent.getActivity(this, 1, intent, 0)); 
    manager.notify(111, notification); 
+1

+1: el uso de setLatestEventInfo() hace que el error desaparezca. Es un poco molesto cuántas líneas de código se necesitan para mostrar una notificación tan simple ... – ArtOfWarfare

0

Para aquellos que están usando NotificationCompat, el siguiente código funcionará:

NotificationCompat.Builder n = new NotificationCompat.Builder(this) 
    .setSmallIcon(R.drawable.icon).setContentText("Notify Title").setContentText("Sample Text"); 
    NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE); 
    Intent i = new Intent(this,MainActivity.class); 
    PendingIntent ac = PendingIntent.getActivity(this, 0, i, 0); 
    n.setContentIntent(ac); 
    nm.notify(12222, n.build()); 
Cuestiones relacionadas