2012-01-27 57 views
10

He intentado obtener una notificación de una carga exitosa desde una ASyncTask para trabajar todo el día. No recibo ningún error de mi código actual, pero no puedo mostrar la notificación en la barra de notificaciones (ni en ningún otro lugar). No recibo mensajes en LogCat y no aparece ninguna notificación en la barra de notificaciones. Este es mi código:notificación de Android no funciona

Notification mNotification = new Notification(icon, tickerText, when); 

CharSequence contentTitle = "upload completed."; 
CharSequence contentText = "upload completed."; 

Intent notificationIntent = new Intent(context, CastrActivity.class); 
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_NO_CREATE); 
mNotification.contentIntent = contentIntent; 
mNotification.setLatestEventInfo(context, contentTitle, contentText, contentIntent); 
mNotificationManager.notify(NOTIFICATION_ID, mNotification); 

Esto se llama desde el método onPostExecute() de un AsyncTask. Estoy un poco confundido en la parte PendingIntent, para ser honesto. Cualquier aclaración de lo que sospecho que es un código incorrecto sería muy apreciada.

Respuesta

4

He creado la clase para mostrar notificaciones:

public class NotificationData { 

    public static NotificationManager mNotificationManager; 
    public static int SIMPLE_NOTFICATION_ID; 
    private Context _context; 

    public NotificationData(Context context) { 
     _context = context; 
    } 

    public void clearNotification() { 
     mNotificationManager.cancel(SIMPLE_NOTFICATION_ID); 
    } 

    public void SetNotification(int drawable, String msg, String action_string, Class cls) { 
     mNotificationManager = (NotificationManager) _context.getSystemService(Context.NOTIFICATION_SERVICE); 
     final Notification notifyDetails = new Notification(drawable, "Post Timer", System.currentTimeMillis()); 
     long[] vibrate = { 100, 100, 200, 300 }; 
     notifyDetails.vibrate = vibrate; 
     notifyDetails.ledARGB = 0xff00ff00; 
     notifyDetails.ledOnMS = 300; 
     notifyDetails.ledOffMS = 1000; 
    // notifyDetails.number=4; 
     notifyDetails.defaults =Notification.DEFAULT_ALL; 
     Context context = _context; 
     CharSequence contentTitle = msg; 
     CharSequence contentText = action_string;  
     Intent notifyIntent = new Intent(context, cls); 
    // Bundle bundle = new Bundle(); 
    // bundle.putBoolean(AppConfig.IS_NOTIFICATION, true); 
     notifyIntent.putExtras(bundle); 
     PendingIntent intent = PendingIntent.getActivity(_context, 0,notifyIntent, android.content.Intent.FLAG_ACTIVITY_NEW_TASK); 
     notifyDetails.setLatestEventInfo(context, contentTitle, contentText, intent); 
     mNotificationManager.notify(SIMPLE_NOTFICATION_ID, notifyDetails);   
    } 
} 

Cómo utilizar esta clase:

NotificationData notification; //create object 
notification = new NotificationData(this); 
notification.SetNotification(R.drawable.notification, "Notification Title", "Click to open", YourClassName.class); 

Añadir permiso android.permission.VIBRATE

+0

Lo siento, pero ¿qué es AppConfig? ¿Hay alguna biblioteca que deba incluir para usar eso? Eclipse no parece saberlo si lo hay, así que tendría que agregarlo a mi ruta de compilación. – Carnivoris

+0

Appconfig es una clase y IS_NOTIFICATION es un miembro estático; puede eliminar esta línea Bundle bundle = new Bundle(); bundle.putBoolean (AppConfig.IS_NOTIFICATION, true); notifyIntent.putExtras (paquete); –

+0

Desafortunadamente, todavía no recibo ninguna notificación. Lo estoy llamando desde el método onPostExecute() de una clase ASyncTask. Confirmo que ASyncTask está completo con un mensaje en LogCat, pero no recibo ninguna notificación enviada a la barra de notificaciones. – Carnivoris

2

Prueba esto:

NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 

int icon = R.drawable.icon;  // icon from resources 
CharSequence tickerText = "Any thing";    // ticker-text 
long when = System.currentTimeMillis();   // notification time 
Context context21 = getApplicationContext();  // application Context 
CharSequence contentTitle = "Anything"; // expanded message title 
CharSequence contentText = (CharSequence) extras.get("message");  // expanded message text 

Intent notificationIntent = new Intent(this, MainStart.class); 
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); 

// the next two lines initialize the Notification, using the configurations above 
Notification notification = new Notification(icon, tickerText, when); 
notification.defaults |= Notification.DEFAULT_VIBRATE; 
notification.defaults |= Notification.DEFAULT_LIGHTS; 
notification.defaults |= Notification.DEFAULT_SOUND; 
notification.flags |= Notification.FLAG_AUTO_CANCEL; 
/* long[] vibrate = { 0, 100, 200, 300 }; 
notification.vibrate = vibrate; 
notification.ledARGB = Color.RED; 
notification.ledOffMS = 300; 
notification.ledOnMS = 300;*/ 
notification.setLatestEventInfo(context21, contentTitle, contentText, contentIntent); 
mNotificationManager.notify(Constants.NOTIFICATION_ID, notification); 
+0

Estoy teniendo problemas similares con esto como lo he hecho antes. Intent notificationIntent = new Intent (esto, CastrRecorder.class); Esa línea se marca con Eclipse y la única solución es eliminar los argumentos. Además, esto se llama dentro de una clase que extiende ASyncTask y getActivity() no funciona. – Carnivoris

2

Otra cosa es tratar de asegurarse de que su manifiesto contiene

<permission android:name="android.permission.STATUS_BAR_SERVICE" android:protectionLevel="signature" /> 

también la mía parecía hacer caso omiso de las notificaciones sucesivas con el mismo NOTIFICATION_ID.

30

A pesar de que el problema está resuelto, sólo voy a publicar cómo resolví mi problema que la notificación no estaba mostrando, tal vez podría ayudar a otras personas a leer las respuestas:

en mi edificio notificación de que me estaba perdiendo la icono. Tan pronto como agregué algo como setSmallIcon(R.drawable.ic_launcher), se mostró la notificación.

+0

tiene exactamente el mismo problema .. resuelto, gracias! – akhyar

+0

Sí, funcionó bien para mí. Primera vez trabajando con notificaciones.¡Muchas gracias! –

+0

¡Exactamente! ¡Muchas gracias! – Alexandr

0

Para mí esto sucedía y no tenía idea de por qué, pero el problema era que el ícono que establecí era demasiado grande, por lo que me estaba dando un error aleatorio.

Cuestiones relacionadas