¿Cómo realizar una acción de notificación (clic) en la pantalla de bloqueo?
TL, DR
¿Cómo puedo hacer una notificación que funcione desde la pantalla de bloqueo sin desbloquear? Después de hacer clic en una acción, un botón en la notificación o simplemente la notificación completa, quiero hacer una llamada a la API (sin escribir mi código de desbloqueo)
Detalles
Gol
Sobre la base de la respuesta sobre esta pregunta he intentado hacer una notificación con una acción que funciona en la lockscreen sin desbloquear el dispositivo. La acción es algo que no necesita ninguna interfaz o interacción adicional (piense en "enviar una solicitud de API").
- Cómo recuperar llamadas perdidas en Android SDK 2.2
- No se puede establecer el sonido de notificación push en android
- Mostrar siempre servicio en la barra de notificación
- Android Cómo abrir la última actividad al hacer tapping en la notificación
- Android Facebook SDK - Cómo consultar las notificaciones de Facebook
Estado
La notificación y el clic funcionan con un dispositivo desbloqueado. Sin embargo, cuando está bloqueado todavía necesito incorporar el código de desbloqueo primero, así que o hay algo nuevo que pasa, o apenas malinterpreté la manera que se supone para trabajar.
Si entiendo correctamente puedo establecer mi visibilidad en 'público' para mostrar el contenido (esto funciona), y en lugar de definir una acción (que no parece ser pública) puedo manejar clics en el diseño (ahora visible). He intentado esto con el siguiente código, pero obviamente no funciona.
He intentado enviar la intención a mi aplicación ya un servicio, como sugiere Florian a continuación.
Código
Éste es el código donde comienzo la notificación (esto vive en una actividad, el código fue acortado para su conveniencia)
private void startNotification() { NotificationCompat.Builder builder = new NotificationCompat.Builder(this) .setVisibility(Notification.VISIBILITY_PUBLIC) .setOngoing(true) .setSmallIcon(R.drawable.abc_ic_menu_share_mtrl_alpha) .setContentTitle("title text") .setContentText("content text"); Intent openIntent = new Intent(MyMainActivity.this, MyMainActivity.class); openIntent.setAction("some_string"); PendingIntent pOpenIntent = PendingIntent.getActivity(this, 0, openIntent, 0); builder.setContentIntent(pOpenIntent); RemoteViews view = new RemoteViews(getPackageName(), R.layout.notification); builder.setContent(view); NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); mNotificationManager.notify(id, builder.build()); }
Como se dijo, también traté con el servicio como Florian sugirió, con esto como una llamada:
Intent yepIntent = new Intent(this, MyIntentService.class); yepIntent.setAction("test"); yepIntent.putExtra("foo", true); yepIntent.putExtra("bar", "more info"); PendingIntent yepPendingIntent = PendingIntent.getService(this, notificationId, yepIntent, PendingIntent.FLAG_CANCEL_CURRENT); //builder.addAction(R.drawable.abc_ic_menu_share_mtrl_alpha, "My Action", yepPendingIntent); builder.setContentIntent(yepPendingIntent);
La acción no apareció en la pantalla de bloqueo, por lo que cambié a la setContentIntent
usted ve arriba. El resultado es el mismo sin embargo, ninguna acción para mí 🙁
- Icono de notificación de Android dinámico
- Problema pendiente de notificación de Android android
- Android: notificación incorrecta publicada sólo en Android 2.3
- ¿Cómo hacer un icono en la barra de acción con el número de notificación?
- Cómo utilizar exactamente Notification.Builder
- Android .setColor para Icono grande
- Escuchando la notificación en Android
- Android - launchMode = singleTask y Notificaciones?
Intente usar un IntentService . Reemplace su objetivo de intención con su servicio de intención:
Intent yepIntent = new Intent(context, MyIntentService.class); yepIntent.putExtra("foo", true); yepIntent.putExtra("bar", "more info"); PendingIntent yepPendingIntent = PendingIntent.getService(context, notificationId, yepIntent, PendingIntent.FLAG_CANCEL_CURRENT); notificationBuilder.addAction(R.drawable.icon_of_choice, "My Action", yepPendingIntent);
Registre su servicio en el Manifiesto:
<service android:name="app.great.mypackage.MyIntentService" android:exported="false"/>
Su Servicio podría tener este aspecto:
public class MyIntentSerice extends IntentService { @Override protected void onHandleIntent(Intent intent) { Log.d("myapp", "I got this awesome intent and will now do stuff in the background!"); // .... do what you like } }
ACTUALIZACIÓN con comentarios de Nanne
El truco parece ser
- Utilice un servicio
- Agregue la intención no como una acción o un ContentIntent, sino con el método RemoteViews.
Combinado será:
NotificationCompat.Builder builder = new NotificationCompat.Builder(this) .setVisibility(Notification.VISIBILITY_PUBLIC) .setOngoing(true) .setSmallIcon(R.drawable.abc_ic_menu_share_mtrl_alpha) .setContentTitle("My notification") .setContentText("Hello World!"); int notificationId = 1; Intent yepIntent = new Intent(this, MyIntentService.class); yepIntent.setAction("test"); yepIntent.putExtra("foo", true); yepIntent.putExtra("bar", "more info"); PendingIntent yepPendingIntent = PendingIntent.getService(this, notificationId, yepIntent, PendingIntent.FLAG_CANCEL_CURRENT); // doesn't show up on my lock-screen //builder.addAction(R.drawable.abc_ic_menu_share_mtrl_alpha, "My Action", yepPendingIntent); // asks for unlock code for some reason //builder.setContentIntent(yepPendingIntent); // Bingo RemoteViews view = new RemoteViews(getPackageName(), R.layout.notification); view.setOnClickPendingIntent(R.id.notification_closebtn_ib, yepPendingIntent); builder.setContent(view);
Combinando la respuesta de la pregunta que enlazé (el botón de la acción de la notificación no clickable en la pantalla de la cerradura ) y el @florian_barth dio arriba, lo conseguí el trabajar
El truco parece ser
- Utilice un servicio
- Agregue la intención no como una acción o un ContentIntent, sino con el método
RemoteViews
.
Combinado será:
NotificationCompat.Builder builder = new NotificationCompat.Builder(this) .setVisibility(Notification.VISIBILITY_PUBLIC) .setOngoing(true) .setSmallIcon(R.drawable.abc_ic_menu_share_mtrl_alpha) .setContentTitle("My notification") .setContentText("Hello World!"); int notificationId = 1; Intent yepIntent = new Intent(this, MyIntentService.class); yepIntent.setAction("test"); yepIntent.putExtra("foo", true); yepIntent.putExtra("bar", "more info"); PendingIntent yepPendingIntent = PendingIntent.getService(this, notificationId, yepIntent, PendingIntent.FLAG_CANCEL_CURRENT); // doesn't show up on my lock-screen //builder.addAction(R.drawable.abc_ic_menu_share_mtrl_alpha, "My Action", yepPendingIntent); // asks for unlock code for some reason //builder.setContentIntent(yepPendingIntent); // Bingo RemoteViews view = new RemoteViews(getPackageName(), R.layout.notification); view.setOnClickPendingIntent(R.id.notification_closebtn_ib, yepPendingIntent); builder.setContent(view);
También funciona con Broadcast receiver y setAction
PendingIntent pendingIntent = PendingIntent.getBroadcast(.. builder.addAction(.. .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
En la pantalla de bloqueo deslice el dedo hacia abajo sobre la notificación para expandirla y toque el área de acción para invocar al receptor de difusión sin desbloquear el teléfono.
- Android: Radio de red desactivada antes del evento ACTION_SHUTDOWN. Orden de cambios modificada en ICS
- Cómo obtener acceso a la API de phonegap desde una página remota