2012-09-23 18 views
8

Hola quiero mostrar todas las notificaciones en una sola vista ... y quiero actualizar el número de notificaciones en la barra de estado ... está actualizando toda la información pero mostrando el número siempre 1 ... por favor dígame cómo para resolverlo ...Cómo actualizar el número de notificación

@Override 
public void onReceive(Context context, Intent intent) 
{ 
    //Random randGen = new Random(); 
    //int notify_id = randGen.nextInt(); 
    NotificationManager notificationManager = (NotificationManager) 
     context.getSystemService(Activity.NOTIFICATION_SERVICE); 
    String title = intent.getStringExtra(TableUtils.KEY_TITLE); 
    String occasion = intent.getStringExtra(TableUtils.KEY_OCCASION); 
    Notification notification = 
     new Notification(R.drawable.icon, "Love Cardz" , 
         System.currentTimeMillis()); 
    // notification.vibrate = new long[]{100,250,300,330,390,420,500}; 
    notification.flags |= Notification.FLAG_AUTO_CANCEL; 
    notification.number+=1; 
    Intent intent1 = new Intent(context, ThemesBrowserActivity.class); 
    PendingIntent activity = 
     PendingIntent.getActivity(context, 1 , intent1, 
            PendingIntent.FLAG_UPDATE_CURRENT); 
    notification.setLatestEventInfo(context, occasion, title, activity); 
    notificationManager.notify(1, notification); 
} 

Respuesta

18

Debes realizar un seguimiento del recuento. Se podría ampliar la clase de aplicación:

public class AppName extends Application { 
    private static int pendingNotificationsCount = 0; 

    @Override 
    public void onCreate() { 
     super.onCreate(); 
    } 

    public static int getPendingNotificationsCount() { 
     return pendingNotificationsCount; 
    } 

    public static void setPendingNotificationsCount(int pendingNotifications) { 
     pendingNotificationsCount = pendingNotifications; 
    } 
} 

Y hay que modificar el OnReceive:

@Override 
public void onReceive(Context context, Intent intent) { 
    ... 
    int pendingNotificationsCount = AppName.getPendingNotificationsCount() + 1; 
    AppName.setPendingNotificationsCount(pendingNotificationsCount); 
    notification.number = pendingNotificationsCount; 
    ... 
} 

Y se podría restablecer el recuento cuando el usuario abra la notificación:

AppName.setPendingNotificationsCount(0); 
+12

Bastante ridículo lo el framework no tiene una simple llamada 'getNotifications (int id)' para simplemente verificar esto ... – clu

+5

Desafortunadamente, si la aplicación ha sido eliminada, el contador se reinicia ... Probablemente debería guardarlo en SharedPreference for persistence – xnagyg

+1

¿Cómo se puede saber cuándo se abrió la notificación para restablecer el contador ...? – Micro

4

Este es mi código, y funciona. Solo he probado en viejas versiones de Android. Sospecho que en las versiones más nuevas, la insignia de "número" se ha vuelto invisible, pero no he tenido la oportunidad de probarla.

void notifyMsgReceived(String senderName, int count) { 
    int titleResId; 
    String expandedText, sender; 

    // Get the sender for the ticker text 
    // i.e. "Message from <sender name>" 
    if (senderName != null && TextUtils.isGraphic(senderName)) { 
     sender = senderName; 
    } 
    else { 
     // Use "unknown" if the sender is unidentifiable. 
     sender = getString(R.string.unknown); 
    } 

    // Display the first line of the notification: 
    // 1 new message: call name 
    // more than 1 new message: <number of messages> + " new messages" 
    if (count == 1) { 
     titleResId = R.string.notif_oneMsgReceivedTitle; 
     expandedText = sender; 
    } 
    else { 
     titleResId = R.string.notif_missedCallsTitle; 
     expandedText = getString(R.string.notif_messagesReceivedTitle, count); 
    } 

    // Create the target intent 
    final Intent intent = new Intent(this, TargetActivity.class); 
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
    final PendingIntent pendingIntent = 
     PendingIntent.getActivity(this, REQUEST_CODE_MSG_RECEIVED, intent, PendingIntent.FLAG_UPDATE_CURRENT); 

    // Build the notification 
    Notification notif = new Notification(
     R.drawable.ic_notif_msg_received, // icon 
     getString(R.string.notif_msgReceivedTicker, sender), // tickerText 
     System.currentTimeMillis()); // when 
     notif.setLatestEventInfo(this, getText(titleResId), expandedText, pendingIntent); 
    notif.number = count; 
    notif.flags = Notification.FLAG_AUTO_CANCEL; 

    // Show the notification 
    mNotificationMgr.notify(NOTIF_MSG_RECEIVED, notif); 
} 

También es fácil actualizar la notificación más adelante: solo tiene que volver a llamar al método con nuevos valores. El número se mostrará en la insignia del icono de notificación si y solo si fue mayor que cero cuando se creó la notificación.

De manera similar, la insignia del número no se ocultará (el número será, usted) si establece el número en un número que sea menor que 1. Tal vez borrar la notificación antes de volver a mostrarla podría solucionarlo.

0

Debes realizar un seguimiento del recuento. El incremento que intenta realizar en notif.number no funciona, ya que ese estado no está disponible (es decir, notif.number siempre es 0, luego lo incrementa a 1). Mantener un registro de número en algún lugar de su aplicación (preferencias compartidas, tal vez), e incremento y almacenarla allí, a continuación, cuando se genera la notificación, establezca

notif.number = myStoredValueForWhatShouldShowInNumber; 

Inténtelo.

Cuestiones relacionadas