2010-10-19 19 views

Respuesta

18

Usted debe ser capaz de hacer esto con la Notificación y la NotificationManager. Sin embargo, obtener una forma garantizada de saber cuándo su aplicación no se está ejecutando es la parte difícil.

, usted 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 onCreate() del Objeto de aplicación personalizado de su aplicación.

Sin embargo, después de eso las cosas son complicadas. La muerte de la aplicación puede suceder en cualquier momento. Así que puedes intentar poner algo en el onTerminate() de la clase Application también, pero no se garantiza que se invoque.

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

será lo que se necesita para eliminar el ícono.

+5

'Notificación 'ha quedado obsoleto en el nivel 11 de API. Use Notification.Builder en su lugar. –

+0

Si usa además 'Servicio', no tiene que eliminar manualmente la notificación.Cuando se detiene el servicio, la notificación se eliminará automáticamente. ("Sin embargo, si detiene el servicio mientras se está ejecutando en primer plano, también se eliminará la notificación." Https://developer.android.com/guide/components/services.html#Foreground) –

6

Eche un vistazo a la Guía de desarrollo "Creating Status Bar Notifications".

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

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); 
    } 
} 
+0

Esto solo le mostrará si una determinada actividad se está ejecutando. No si la aplicación aún se está ejecutando. –

+0

@Greg: Correcto, este código de ejemplo solo maneja correctamente una aplicación de una actividad. Es mucho más difícil determinar cuándo el sistema ha matado a la aplicación. Como mencionaste, una clase 'Application' personalizada es probablemente el mejor lugar para el código ya que persiste durante toda la vida de la aplicación. La eliminación de la notificación será difícil porque el sistema puede decidir arbitrariamente matar el proceso de una aplicación en condiciones de poca memoria. Puede intentar crear un servicio para supervisar el estado ya que el sistema intentará reiniciar el servicio más tarde cuando haya más memoria disponible. – Brian

+0

Si elimina 'notificationManager.cancel (NOTIFICATION_EX);' from 'onPause', la notificación permanecerá en la barra de notificaciones hasta que la aplicación se haya detenido por completo. –

8

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 puede cancelar su notificación llamando al

mNotifyMgr.cancel(NOTIFICATION_ID); 
+0

lo que hará ser el contenido de MyActivity.class? @mjosh –

+0

@Sarahcartenz Todo lo que quieras realmente – mjosh

+0

¿Qué sucede si no defino una clase así? o mantenerlo vacío. No quiero una acción una vez que se presiona la notificación, por ejemplo. –

3

Realmente funciona. I 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);

+0

si puedo preguntar, ¿cuál será el contenido de ActMain.class? –

Cuestiones relacionadas