2011-04-04 16 views
11

estoy creando una notificación de un servicio con el siguiente código:Haga clic en la notificación se inicia la actividad dos veces

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

CharSequence tickerText = "bla ..."; 
long when = System.currentTimeMillis(); 
Notification notification = new Notification(R.drawable.icon, 
tickerText, when); 

Intent notificationIntent = new Intent(ctx, SearchActivity.class). 
putExtra(SearchActivity.INTENT_SOURCE, 
MyNotificationService.class.getSimpleName()); 

PendingIntent contentIntent = PendingIntent.getActivity(ctx, 0, 
notificationIntent, 0); 
notification.setLatestEventInfo(ctx, ctx.getString(R.string.app_name), 
tickerText, contentIntent); 
notification.flags |= Notification.FLAG_AUTO_CANCEL; 
notificationManager.notify(1, notification); 

Los registros claramente dice que el startActivity El método se llama el doble de veces:

04-02 23:48:06.923: INFO/ActivityManager(2466): Starting activity: Intent { act=android.intent.action.SEARCH cmp=com.xy/.SearchActivity bnds=[0,520][480,616] (has extras) } 
04-02 23:48:06.923: WARN/ActivityManager(2466): startActivity called from non-Activity context; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: Intent { act=android.intent.action.SEARCH cmp=com.xy/.SearchActivity bnds=[0,520][480,616] (has extras) } 
04-02 23:48:06.958: INFO/ActivityManager(2466): Starting activity: Intent { act=android.intent.action.SEARCH cmp=com.xy/.SearchActivity bnds=[0,0][480,96] (has extras) } 
04-02 23:48:06.958: WARN/ActivityManager(2466): startActivity called from non-Activity context; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: Intent { act=android.intent.action.SEARCH cmp=com.xy/.SearchActivity bnds=[0,0][480,96] (has extras) } 
04-02 23:48:07.087: INFO/notification(5028): onStartCmd: received start id 2: Intent { cmp=com.xy/.NotificationService } 
04-02 23:48:07.310: INFO/notification(5028): onStartCmd: received start id 3: Intent { cmp=com.xy/.NotificationService } 
04-02 23:48:07.392: INFO/ActivityManager(2466): Displayed activity com.xy/.SearchActivity: 462 ms (total 462 ms) 
04-02 23:48:07.392: INFO/ActivityManager(2466): Displayed activity com.xy/.SearchActivity: 318 ms (total 318 ms) 

¿Por qué se comenzaron dos veces?

Hay dos preguntas idénticas en stackoverflow: here y here. Pero no explican cuál podría ser el problema inicial y no funcionan para mí. P.ej. cambiar a launchMode singleTop no es apropiado para mí y debería funcionar sin cambiar launchMode de acuerdo con official docs (consulte Invocar el cuadro de diálogo de búsqueda).

Sin embargo también he intentado añadir las siguientes banderas para notificationIntent

Intent.FLAG_ACTIVITY_CLEAR_TOP | PendingIntent.FLAG_UPDATE_CURRENT

pero el problema sigue siendo el mismo.

+0

Creo un proyecto de prueba desde cero y existe el mismo problema allí (en el dispositivo Samsung). Para el emulador (2.1 + 2.2) todo parece estar bien. – Karussell

Respuesta

14

Igual en este caso, ocurre un problema en Samsung Galaxy S. ¿Alguna buena idea para una solución alternativa?

Estoy comprobando si ya se recibió una intención similar y finalizo la actividad si es así. Funciona, pero no se ve muy bien.

¿Podemos de alguna manera cancelar el segundo intento?

ACTUALIZACIÓN: podía evitar que el problema estableciendo la FLAG_ONE_SHOT así:

PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT); 
+0

¡Agradable! gracias por confirmar esto Esto me llevó casi loco :) Actualizaré mi respuesta para una solución – Karussell

0

Esto parece ser un error de la galaxia de Samsung. Confirmó que todo está bien en un dispositivo diferente.

(Véase también no discussion at google groups)

Una solución puede ser para cancelar la segunda intención con el truco torpe pero trabajando (no estoy seguro si esto tiene efectos secundarios en otros dispositivos):

// put a hint into the notification and check if the intent 
// comes from notification or not: 
String intentSource = queryIntent.getStringExtra(INTENT_SOURCE); 
if (NotificationService.class.getSimpleName().equals(intentSource)) { 
// don't do this again e.g. when rotating! 
queryIntent.removeExtra(INTENT_SOURCE); 

if (getIntent() != null && getIntent().getSourceBounds() != null) { 
    if (getIntent().getSourceBounds().top == 0 
      && getIntent().getSourceBounds().left == 0) { 
     Log.w("search", "Problematic double trigger!"); 
    } 
} 
} 

a fin de utilizar esto con cuidado y, probablemente, comprobar si se hizo un clic anterior en el último segundo, entonces es muy probable que sea el problema de doble desencadenante.

1

llaman por clave liberado o tecla pulsada (evitar la acción general)!

if(event.getAction() == event.ACTION_UP){ 
    Intent intent = new Intent(......); 
    startActivityForResult(intent, 0); 
} 
5

Utilice la bandera de la siguiente manera.

notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP 
          |Intent.FLAG_ACTIVITY_SINGLE_TOP); 
+3

Esto no funciona con ** PendingIntent ** – swiftBoy

Cuestiones relacionadas