studio priority overview notification ejemplo anatomy android notifications

priority - Al hacer clic en Acciones de notificación de Android no se cierra Cajón de notificación



notification overview android (5)

Aunque aprecio mucho que la respuesta de Soumyajyoti sea correcta ... de hecho no es ...

estoy usando

Intent CR = new Intent(CRCODE); PendingIntent.getBroadcast(getApplicationContext(), MY_ID, CR, 0);

en un diseño de vista remota para una notificación en curso ...

Puedo asegurarle que no cierra el cajón, pero activa el intento y dibuja la actividad detrás del cajón abierto, además de realizar las otras tareas que le asigné a mi receptor ...

He probado tanto getActivity, como getService (ninguno de los cuales funcionará en mi circunstancia, necesito disparar varios intentos onRecieve) y ambos cierran el cajón correctamente ...

Sé que esta no es una respuesta, pero cuando y si la encuentro me reportaré para editar esto ...

Pensamiento loco ... tal vez una actividad sin contenido visual podría llamarse como un receptor de difusión que dispararía los intentos apropiados a otras clases o aplicaciones según sea necesario ...

el loco pensamiento mencionado arriba funciona ... inicia una actividad con PendingIntent.getActivity y la usa para retransmitir transmisiones u otras intenciones, luego se termina a sí mismo ... el efecto no es directo, sino que es imperceptible para el usuario final

Estoy agregando una barra de notificación al sistema usando la biblioteca NotificationCompat . Esta notificación tiene dos botones de acción. Además, la propiedad AutoCancel() en la notificación se establece en verdadero.

Al hacer clic en los botones de acción, el sistema se configura para iniciar un servicio de IntentService que llama a NotificationManager.cancel(NOTIFICATION_ID) y luego inicia una actividad en una nueva tarea.
El problema es que aunque esta llamada elimina la notificación de la bandeja, no colapsará el cajón. La actividad llamada se dibuja detrás del cajón.

¿Puede alguien arrojar algo de luz sobre qué código especial se necesita para cerrar el sorteo aparte de cancelar la notificación?

Gracias.


Descubrí que cuando usa los botones de acción en las notificaciones expandidas, tiene que escribir un código adicional y está más limitado.

Antes de usar notificaciones expandidas, la acción predeterminada en mi notificación de descarga de archivos era iniciar una actividad VER en el archivo. El intento de VER estaba envuelto por un intento de Selector. No pude usar un intento pendiente para la intención del Selector directamente de la notificación porque el Selector se bloqueaba si no había actividad para ver el tipo de archivo. Así que tenía un BroadcastReceiver que iniciaría la intención del Selector.

Con las notificaciones expandidas, decidí cambiar la notificación de descarga de archivos, por lo que la acción predeterminada es mostrar la actividad de detalles del archivo, con botones de acción para Ver y Enviar. Como señaló el usuario 2536953, iniciar un receptor de difusión desde la notificación no cierra el cajón de notificaciones. Basado en su información de que una actividad cerraría el cajón, cambié mi receptor de difusión a una actividad de notificación sin ninguna interfaz de usuario.

Como se indica en esta publicación Cómo descartar la notificación de Android después de haber hecho clic en la acción , otro problema es que debe cancelar manualmente su notificación cuando el usuario haga clic en un botón de acción. La notificación solo se cancela automáticamente para la acción predeterminada. También agregué código en NotificationActivity para manejar esto.

Creando la notificación expandida con los botones de vista y envío:

NotificationCompat.Builder builder = new NotificationCompat.Builder(m_context).setAutoCancel(true); final PendingIntent contentIntent = DownloadedFileIntentUtils.buildPendingItemDetailIntent(m_context, item); builder.setContentIntent(contentIntent); PendingIntent viewIntent = DownloadedFileIntentUtils.buildNotificationActionIntent(m_context, Intent.ACTION_VIEW, m_context.getString(R.string.action_open), uri, MimeTypeUtil.getMimeType(item), id); builder.addAction(R.drawable.actionbar_open_with, m_context.getString(R.string.action_open), viewIntent); PendingIntent sendIntent = DownloadedFileIntentUtils.buildNotificationActionIntent(m_context, Intent.ACTION_SEND, m_context.getString(R.string.action_send), uri, MimeTypeUtil.getMimeType(item), id); builder.addAction(R.drawable.actionbar_share, m_context.getString(R.string.action_send), sendIntent); builder.setTicker(title) .setContentTitle(title) .setContentText(text) .setSmallIcon(R.drawable.notification_download); .setStyle(new NotificationCompat.BigTextStyle().bigText(text)); getNotificationManager().notify(id, builder.build());

Desarrollar la intención de iniciar una actividad desde los botones de acción de notificación:

public static PendingIntent buildNotificationActionIntent(Context context, String action, String actionTitle, Uri uri, String mimeType, int notificationId) { // Build the file action intent (e.g. VIEW or SEND) that we eventually want to start. final Intent fileIntent = buildFileActionIntent(action, actionTitle, uri, mimeType); // Build the intent to start the NotificationActivity. final Intent notificationIntent = new Intent(context, NotificationActivity.class); // This flag must be set on activities started from a notification. notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // Pass the file action and notification id to the NotificationActivity. notificationIntent.putExtra(Intent.EXTRA_INTENT, fileIntent); notificationIntent.putExtra(IIntentCode.INTENT_EXTRA_NOTIFICATION_ID, notificationId); // Return a pending intent to pass to the notification manager. return PendingIntent.getActivity(context, s_intentCode.getAndIncrement(), notificationIntent, PendingIntent.FLAG_ONE_SHOT); } public static Intent buildFileActionIntent(String action, String actionTitle, Uri uri, String mimeType) { Intent intent = new Intent(action); intent.addCategory(Intent.CATEGORY_DEFAULT); if (action.equals(Intent.ACTION_SEND)) { intent.putExtra(Intent.EXTRA_STREAM, uri); intent.setType(mimeType); } else { intent.setDataAndType(uri, mimeType); } intent.putExtra(Intent.EXTRA_TITLE, actionTitle); // Grant read permission on the file to other apps without declared permission. int flags = Intent.FLAG_GRANT_READ_URI_PERMISSION; intent.setFlags(flags); return intent; }

Actividad de notificación sin UI:

public class NotificationActivity extends Activity { private final static Logger s_logger = LogUtil.getLogger(NotificationActivity.class); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = getIntent(); // Cancel the notification that initiated this activity. // This is required when using the action buttons in expanded notifications. // While the default action automatically closes the notification, the // actions initiated by buttons do not. int notificationId = intent.getIntExtra(IIntentCode.INTENT_EXTRA_NOTIFICATION_ID, -1); if (notificationId != -1) { NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); manager.cancel(notificationId); } // If there is an activity to handle the action, start the file action. if (DownloadedFileIntentUtils.verifyActivityIsAvailable(this, fileActionIntent, false)) { fileActionIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); DownloadedFileIntentUtils.startFileActionActivity(this, fileActionIntent); } // Finish activity. finish(); } public static void startFileActionActivity(Context context, Intent fileActionIntent) { // Start chooser intent. Intent chooser = Intent.createChooser(fileActionIntent, fileActionIntent.getStringExtra(Intent.EXTRA_TITLE)); // Copy the flags from fileActionIntent to chooser intent. // FileActionExecutor must set FLAG_ACTIVITY_NEW_TASK on the intent passed to startActivity // because the flag is required when starting an activity from a context that is not an activity. chooser.addFlags(fileActionIntent.getFlags()); context.startActivity(chooser); }

No olvide agregar NotificationActivity to AndroidManifest.xml.


El sistema de Android colapsa el cajón de notificaciones cada vez que hace clic en una notificación e inicia una actividad o transmisión. No creo que haya ninguna forma programática de cerrar el cajón de notificaciones con tu código. Le sugiero que compruebe las intenciones que pasa al creador de notificaciones y asegúrese de que se les den las intenciones de referencia correctas. Creo que algo dentro del administrador de notificaciones de Android está siendo bloqueado debido a la intención que brindas. Hasta ahora no he visto el cajón de notificaciones abierto una vez que la acción se desencadena a partir de la notificación. Simplemente con curiosidad por saber si su actividad objetivo tiene un área semitransparente donde la actividad anterior es visible, si es así, le sugiero que haga que el fondo sea completamente opaco (sin una región transparente / semi transparente). Puede ser que esté impidiendo que el iniciador de Android home complete la secuencia de detención y, por lo tanto, no permita que el iniciador cierre el cajón de notificaciones por usted. Espero haber podido ayudarte. Todo lo mejor.


Si su acción es en forma de transmisión o servicio, pero tiene la intención de colapsar el cajón de notificaciones, debe transmitir android.intent.action.CLOSE_SYSTEM_DIALOGS de su onReceive. Esto cerrará manualmente el cajón.


prueba esto:

NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(getApplicationContext().NOTIFICATION_SERVICE); Intent notificationIntent = new Intent(this.getBaseContext(), MainActivity.class); notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); NotificationCompat.Builder mNotifyBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder( getApplicationContext()) .setTicker(getApplicationContext().getText(R.string.app_name)) .setContentTitle(getApplicationContext().getText(R.string.app_name)) .setContentText(getApplicationContext().getText(R.string.text)) .setSmallIcon(R.drawable.smallicon) .setLargeIcon(BitmapFactory.decodeResource(getApplicationContext().getResources(), R.mipmap.ic_launcher)) .setContentIntent(pendingIntent) .setAutoCancel(true) .setVibrate(new long[]{150, 300}); mNotifyBuilder.build().flags |= Notification.FLAG_AUTO_CANCEL; notificationManager.notify(1, mNotifyBuilder.build());