Cómo mostrar un icono en la barra de estado cuando se ejecuta la aplicación, incluyendo en el fondo?

StackOverflow https://stackoverflow.com/questions/3973208

Pregunta

Quiero poner un icono en la barra de estado cuando cada vez que mi aplicación se está ejecutando, incluyendo cuando se está ejecutando en segundo plano. ¿Cómo puedo hacer esto?

¿Fue útil?

Solución

debería ser capaz de hacer esto con la Notificación y la NotificationManager. Sin embargo conseguir una forma garantizada para saber cuando su aplicación no se está ejecutando es la parte difícil.

Se puede obtener la funcionalidad básica de lo que está deseando haciendo algo como:

Notification notification = new Notification(R.drawable.your_app_icon,
                                             R.string.name_of_your_app, 
                                             System.currentTimeMillis());
notification.flags |= Notification.FLAG_NO_CLEAR
                   | Notification.FLAG_ONGOING_EVENT;
NotificationManager notifier = (NotificationManager)
     context.getSystemService(Context.NOTIFICATION_SERVICE);
notifier.notify(1, notification);

Este código debe estar en algún lugar en el que está seguro va a ser despedido cuando se inicia la aplicación. Posiblemente en el método de objeto de aplicación personalizada de la aplicación onCreate ().

Sin embargo después de que las cosas son difíciles. La matanza de la aplicación puede ocurrir en cualquier momento. Así que usted puede tratar de poner algo en el onTerminate () de la clase de aplicación también, pero no se garantiza que se llamará.

((NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE)).cancel(1);

será lo que se necesita para eliminar el icono.

Otros consejos

Para la nueva API que puede utilizar NotificationCompat.Builder -

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
    .setSmallIcon(R.mipmap.ic_launcher)
    .setContentTitle("Title");
Intent resultIntent = new Intent(this, MyActivity.class);
PendingIntent resultPendingIntent = PendingIntent.getActivity(
this,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
Notification notification = mBuilder.build();
notification.flags |= Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT;

mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNotifyMgr.notify(NOTIFICATION_ID, notification);

Se mostrará el tiempo que su aplicación se está ejecutando y alguien cierra manualmente su aplicación. Siempre se puede cancelar su notificación llamando -

mNotifyMgr.cancel(NOTIFICATION_ID);

Tome un vistazo a la guía para programadores " Creación de la barra de estado Notificaciones ".

Una forma de lograr el objetivo de mantener el icono no sólo cuando se ejecuta la aplicación es inicializar la notificación de llamada y onCreate() cancel(int) en su método onPause() sólo si vuelve isFinishing() cierto.

Un ejemplo:

private static final int NOTIFICATION_EX = 1;
private NotificationManager notificationManager;

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

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

    int icon = R.drawable.notification_icon;
    CharSequence tickerText = "Hello";
    long when = System.currentTimeMillis();

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

    Context context = getApplicationContext();
    CharSequence contentTitle = "My notification";
    CharSequence contentText = "Hello World!";
    Intent notificationIntent = new Intent(this, MyClass.class);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 
        0, notificationIntent, 0);

    notification.setLatestEventInfo(context, contentTitle, 
        contentText, contentIntent);

    notificationManager.notify(NOTIFICATION_EX, notification);
}

@Override
protected void onPause() {
    super.onPause();
    if (isFinishing()) {
        notificationManager.cancel(NOTIFICATION_EX);
    }
}

Realmente funciona. Creé un método del ejemplo anterior:

private void applyStatusBar(String iconTitle, int notificationId) {
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(iconTitle);
Intent resultIntent = new Intent(this, ActMain.class);
PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
Notification notification = mBuilder.build();
notification.flags |= Notification.FLAG_NO_CLEAR|Notification.FLAG_ONGOING_EVENT;

NotificationManager mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNotifyMgr.notify(notificationId, notification);}

Debería ser llamado como: applyStatusBar ( "Test de estado", 10);

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top