Cómo suprimir la notificación en la pantalla de bloqueo en Android 5 (Lollipop), pero dejarlo en el área de notificación?

Después de la actualización a Android 5.0 Lollipop comenzó a mostrar automáticamente la notificación en curso en la pantalla de bloqueo.

A veces los usuarios no quieren verlos todos, así que están pidiendo a los desarrolladores cómo dejar la notificación en el área de estado, pero ocultarlos en la pantalla de bloqueo.

La única manera que encontré es obligar a los usuarios a usar bloqueo de pantalla (por ejemplo, gesto o PIN) y programaticamente setVisibility () a VISIBILITY_SECRET . Pero no todos ellos quieren usar bloqueo de pantalla.

¿Hay alguna bandera (o combinación de banderas) diciendo a la notificación: no ser visible en la pantalla de bloqueo, pero ser visible en el área de notificación?

Usar visibilidad y prioridad

Tal como está cubierto por esta respuesta , puede utilizar VISIBILITY_SECRET para suprimir la notificación en la pantalla de bloqueo cuando el usuario tiene un bloqueo de teclado seguro (no sólo con un dedo o sin bloqueo de teclado) y se suprimen las notificaciones sensibles.

Para cubrir el resto de los casos, puede ocultar la notificación de la pantalla de bloqueo y la barra de estado mediante la configuración de la prioridad de la notificación a PRIORITY_MIN siempre que el bloqueo de teclado esté presente y restablezca la prioridad siempre que el bloqueo de teclado esté ausente.

Desventajas

  • Usando un emulador de Android 5, esto parece resultar en la notificación muy brevemente que aparece en la pantalla de bloqueo, pero luego desaparece.
  • Ya no funciona desde Android O Developer Preview 2 cuando el usuario no tiene una pantalla de bloqueo segura (por ejemplo, sólo pase) ya que las prioridades de notificación están obsoletas .

Ejemplo

 final BroadcastReceiver notificationUpdateReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE); NotificationCompat.Builder builder = new NotificationCompat.Builder(context); .setVisibility(NotificationCompat.VISIBILITY_SECRET); KeyguardManager keyguardManager = (KeyguardManager)context.getSystemService(Context.KEYGUARD_SERVICE); if (keyguardManager.isKeyguardLocked()) builder.setPriority(NotificationCompat.PRIORITY_MIN); notificationManager.notify(YOUR_NOTIFICATION_ID, notification); } }; //For when the screen might have been locked context.registerReceiver(notificationUpdateReceiver, new IntentFilter(Intent.ACTION_SCREEN_OFF)); //Just in case the screen didn't get a chance to finish turning off but still locked context.registerReceiver(notificationUpdateReceiver, new IntentFilter(Intent.ACTION_SCREEN_ON)); //For when the user unlocks the device context.registerReceiver(notificationUpdateReceiver, new IntentFilter(Intent.ACTION_USER_PRESENT)); //For when the user changes users context.registerReceiver(notificationUpdateReceiver, new IntentFilter(Intent.ACTION_USER_BACKGROUND)); context.registerReceiver(notificationUpdateReceiver, new IntentFilter(Intent.ACTION_USER_FOREGROUND)); 

Parece que VISIBILITY_SECRET hace el enfoque más limpio. Según la documentación:

Se puede hacer una notificación VISIBILITY_SECRET, que suprimirá su icono y ticker hasta que el usuario haya pasado por alto la lockscreen.

Por la fuente (NotificationData en el proyecto SystemUI AOSP), VISIBILITY_SECRET es la única manera de hacerlo:

 boolean shouldFilterOut(StatusBarNotification sbn) { if (!(mEnvironment.isDeviceProvisioned() || showNotificationEvenIfUnprovisioned(sbn))) { return true; } if (!mEnvironment.isNotificationForCurrentProfiles(sbn)) { return true; } if (sbn.getNotification().visibility == Notification.VISIBILITY_SECRET && mEnvironment.shouldHideSensitiveContents(sbn.getUserId())) { return true; } return false; } 

El único otro tipo de notificaciones que parecen ser filtradas son las notificaciones secundarias en un grupo donde hay un resumen. Así que a menos que tenga múltiples razones válidas para un resumen, VISIBILITY_SECRET es lo mejor que se puede hacer actualmente.

Puede establecer la prioridad de la notificación en PRIORITY_MIN . Esto debe ocultar la notificación en la pantalla de bloqueo. También oculta el icono de la barra de estado (no está seguro de si desea que), pero la notificación en sí sigue siendo visible en el área de notificación.

He creado un 'LockscreenIntentReceiver' para mi notificación en curso que se parece a esto:

  private class LockscreenIntentReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { try { String action = intent.getAction(); if (action.equals(Intent.ACTION_SCREEN_OFF)) { Log.d(TAG, "LockscreenIntentReceiver: ACTION_SCREEN_OFF"); disableNotification(); } else if (action.equals(Intent.ACTION_USER_PRESENT)){ Log.d(TAG, "LockscreenIntentReceiver: ACTION_USER_PRESENT"); // NOTE: Swipe unlocks don't have an official Intent/API in android for detection yet, // and if we set ungoing control without a delay, it will get negated before it's created // when pressing the lock/unlock button too fast consequently. Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { if (NotificationService.this.isNotificationAllowed()) { enableNotification((Context)NotificationService.this); } } }, 800); } } catch (Exception e) { Log.e(TAG, "LockscreenIntentReceiver exception: " + e.toString()); } } } 

Este código básicamente eliminará la notificación en curso cuando el usuario bloquea el teléfono (la eliminación será visible muy brevemente). Y una vez que el usuario desbloquea el teléfono, la notificación en curso se restaurará después del tiempo de retardo (800 ms aquí). EnableNotification () es un método que creará la notificación y llamará a startForeground () . Actualmente verificado para trabajar en Android 7.1.1.

Sólo tiene que recordar registrar y anular el registro del receptor en consecuencia.

  • Actividad actual de la aplicación de Android
  • Mostrar siempre servicio en la barra de notificación
  • Mostrar icono pequeño en la barra de estado sin mostrar notificación
  • Notificación de Android Estilo de imagen grande y estilo de texto grande
  • Obtener icono de notificación mediante un servicio de accesibilidad
  • Creación de la notificación de InstrumentationTestCase
  • ¿Es una práctica común preguntar a los usuarios si desean recibir notificaciones push?
  • Cancelación automática de la notificación en un momento determinado
  • El icono de la barra de notificaciones se vuelve blanco en Android 5 Lollipop
  • ¿Se puede manipular el terminal inalámbrico Android sin utilizar un objeto de notificación?
  • Cómo mostrar un mensaje de barra superior en Android
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.