2010-07-28 16 views
13

Tengo una aplicación de Android, cuando ejecuta un servicio, quiero mostrar la notificación en la barra de estado. Luego, el usuario puede navegar a otra aplicación presionando la tecla INICIO. Sin embargo, cuando trato de volver a mostrar la aplicación anterior en ejecución a través del icono de notificación, hay algún problema con la actividad existente. Incluso lo declaro como modo "Single Top" (deseo ejecutar la actividad existente ya que hay un servicio asociado en ejecución), de alguna manera se ha llamado a OnDesesoy de esa actividad antes de OnResume. Aquí está mi código de creación del objeto de notificación. ¿Podrías por favor señalarme qué mal es? Gracias.Cómo llevar la actividad existente de Android al frente a través de la notificación

private void showNotification() 
{ 

    Intent toLaunch = new Intent(getApplicationContext(), 
              MySingleTopActivity.class); 

    PendingIntent intentBack = PendingIntent.getActivity(getApplicationContext(), 0,toLaunch, PendingIntent.FLAG_UPDATE_CURRENT); 

    notification.setLatestEventInfo(getApplicationContext(), 
     getText(R.string.GPS_service_name), text, intentBack); 
.... 
} 
+0

posibles duplicados: http://stackoverflow.com/questions/4047683/android-how-to-resume-an-app-from-a-notification, http://stackoverflow.com/questions/5502427/resume-application-and-stack-from-notification – Philipp

Respuesta

-2

Cuando una actividad está en segundo plano, Android puede matar la actividad en cualquier momento para liberar recursos. Consulte la documentación Activity para obtener detalles completos sobre el ciclo de vida.

Su actividad necesita estar preparada para guardar su estado en los métodos onPause o onSaveInstanceState. El documento al que se hace referencia arriba tiene detalles adicionales sobre cómo guardar el estado persistente.

+1

No creo que la actividad deba ser invocada por "onDestroy". Solo se llama "onPause" cuando pasa al fondo. Y se llama a "onResume" cuando vuelve al frontend. Si simplemente hago clic en el ícono de la aplicación para reiniciar la aplicación, no hay problema, solo se llama a "En espera". Sin embargo, si trato de hacer clic en el icono de notificación, la actividad va "onDestroy" -> "OnResume", eso causa un problema. – user404012

+0

onPause se invoca cuando pasa al segundo plano. Sin embargo, como se indica en el documento al que se hace referencia, Android puede elegir eliminar la Actividad en cualquier momento si necesita los recursos, y así se llamará a onDestroy. No puede depender del hecho de que no se invocará onDestroy, por lo tanto, debe tratarlo adecuadamente guardando el estado. –

23
private void showNotification() { 
    Intent toLaunch = new Intent(getApplicationContext(), MySingleTopActivity.class); 

    //add these two lines will solve your issue 
    toLaunch.setAction("android.intent.action.MAIN"); 
    toLaunch.addCategory("android.intent.category.LAUNCHER"); 

    PendingIntent intentBack = PendingIntent.getActivity(getApplicationContext(), 0, toLaunch, PendingIntent.FLAG_UPDATE_CURRENT); 

    notification.setLatestEventInfo(getApplicationContext(), getText(R.string.GPS_service_name), text, intentBack); 
    ... 
} 
+0

notification.setLatestEventInfo (getApplicationContext(), getText (R.string.GPS_service_name), text, intentBack); el texto debería estar en el lanzamiento, creo ... – Siddhesh

+0

+1 con la mención de que la declaración PendingIntent debe ser 'PendingIntent contentIntent = PendingIntent.getActivity (this, 0, toLaunch, 0);' – Calin

8

te recomiendo hacer esto,

private void showNotification() 
{ 

Intent toLaunch = new Intent(getApplicationContext(), DummyActivity.class); 

// You'd need this line only if you had shown the notification from a Service 
toLaunch.setAction("android.intent.action.MAIN"); 

PendingIntent intentBack = PendingIntent.getActivity(getApplicationContext(), 0,toLaunch, PendingIntent.FLAG_UPDATE_CURRENT); 

.... 
} 

El DummyActivity debe ser simplemente una actividad que siempre termina en sí en caso alcrear.

En el archivo de manifiesto, añadir estas líneas

<activity class=".DummyActivity"> 
    <intent-filter> 
     <action android:name="android.intent.action.MAIN" /> 
    </intent-filter> 
</activity> 

Espero que esto ayude ...

+0

Esta fue la única solución que funcionó para mí en Android 2.2+. Gracias – Darcy

+0

Me alegro de que funcionó :) –

+0

@Sharique Abdullah Esta es una solución muy inteligente, gracias :) – Lev

0

Otra forma de poner en marcha su intención paquete.

private void NotificationwithLaucherSelfPackage(Context context , int notification_id){ 
     Notification noti = new Notification.Builder(context) 
       .setContentTitle("Your Title") 
       .setContentText("Your Text") 
       .setSmallIcon(R.drawable.abc_ic_menu_share_mtrl_alpha) 
       .setContentIntent(PendingIntent.getActivity(context ,notification_id , getLauncherIntent(context) , PendingIntent.FLAG_UPDATE_CURRENT)) 
       .build(); 
     NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE); 
    } 

private Intent getLauncherIntent(Context context){ 
     return context.getPackageManager().getLaunchIntentForPackage(context.getPackageName()); 
    } 
Cuestiones relacionadas