Mostrar notificaciones push cuando la aplicación se abre / cierra de manera diferente

En mi aplicación tengo varias actividades que heredan de una BaseActivity.
Mi aplicación recibe notificación push con GCMBaseIntentService
Necesito implementar la siguiente lógica:
Cuando el push recibido si la aplicación está abierta show dialog, if closed show notification.

Mi código:

  public class GCMIntentService extends GCMBaseIntentService { ----------------------- other code ---------------------------------------- @Override protected void onMessage(Context context, Intent intent) { Log.d(TAG, "onMessage : " + String.valueOf(intent)); // This is how to get values from the push message (data) String payload = intent.getExtras().getString("payload"); String message = ""; String messageID; if (payload.contains("{")) { try { JSONObject jsonArray = new JSONObject(payload); message = jsonArray.get("Msg").toString(); messageID = jsonArray.get("MessageID").toString(); GA_Handler.sendEvent("Popup_Push", String.format("Push message %s", messageID)); } catch (Exception ex) { // Do nothing } } else { message = payload; } // special intent with action we make up Intent pushReceivedIntent = new Intent(ACTION_PUSH); // place old extras in new intent pushReceivedIntent.putExtras(intent.getExtras()); // find out if there any BroadcastReceivers waiting for this intent if (context.getPackageManager().queryBroadcastReceivers(pushReceivedIntent, 0).size() > 0) { // We got at least 1 Receiver, send the intent context.sendBroadcast(pushReceivedIntent); } else { // There are no receivers, show PushNotification as Notification // long timestamp = intent.getLongExtra("timestamp", -1); NotificationManager notificationManager = (NotificationManager) context .getSystemService(Context.NOTIFICATION_SERVICE); Notification note = new Notification(R.drawable.ic_launcher, "MYAPP", System.currentTimeMillis()); Intent notificationIntent = new Intent(context, SplashActivity.class); notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0); note.setLatestEventInfo(context, "MYAPP", message, pendingIntent); note.number = count++; note.defaults |= Notification.DEFAULT_SOUND; note.defaults |= Notification.DEFAULT_VIBRATE; note.defaults |= Notification.DEFAULT_LIGHTS; note.flags |= Notification.FLAG_AUTO_CANCEL; notificationManager.notify(0, note); } } ----------------------- other code ---------------------------------------- } 

En mi BaseActivity:

 @Override protected void onResume() { super.onResume(); //register as BroadcastReceiver for Push Action IntentFilter filter = new IntentFilter(); filter.addAction(GCMIntentService.ACTION_PUSH); mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { DialogFragmentUtils.getNotification("Notification", "Notification"); } }; registerReceiver(mReceiver, filter); } @Override protected void onPause() { super.onPause(); FragmentManager fm = getSupportFragmentManager(); for (int i = 0; i < fm.getBackStackEntryCount(); ++i) { fm.popBackStack(); } //unregister broadcast receiver unregisterReceiver(mReceiver); } 

Siempre recibo las notificaciones.
Cuando context.getPackageManager().queryBroadcastReceivers(pushReceivedIntent, 0).size() el context.getPackageManager().queryBroadcastReceivers(pushReceivedIntent, 0).size() siempre es igual a 0.

¿Puede alguien decirme lo que estoy haciendo mal?

Parece que PackageManager.queryBroadcastReceivers () devuelve todos los receptores declarados en los manifiestos de aplicación que coinciden con un Intentado dado.

Sin embargo, tenga en cuenta que esto no incluirá a los receptores registrados con Context.registerReceiver (); Actualmente no hay forma de obtener información sobre ellos.

Puede utilizar el código siguiente en onReceive () para determinar si la aplicación / actividad se está ejecutando o no

 ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE); List<RunningTaskInfo> taskInfo = am.getRunningTasks(1); Log.d("current task :", "CURRENT Activity ::" + taskInfo.get(0).topActivity.getClass().getSimpleName()); ComponentName componentInfo = taskInfo.get(0).topActivity; if(componentInfo.getPackageName().equalsIgnoreCase("your.package.name")){ //Activity in foreground, broadcast intent } else{ //Activity Not Running //Generate Notification } 

Puede comprobar si la aplicación está en segundo plano o en primer plano utilizando este código:

  public String isApplicationSentToBackground(final Context context) { ActivityManager am = (ActivityManager) context .getSystemService(Context.ACTIVITY_SERVICE); List<RunningTaskInfo> tasks = am.getRunningTasks(1); if (!tasks.isEmpty()) { ComponentName topActivity = tasks.get(0).topActivity; if (!topActivity.getPackageName().equals(context.getPackageName())) { return "false"; } } return "true"; } 

Si devuelve "true" y luego mostrar la notificación, aparecerá el cuadro de diálogo.

Cuando depuro el context.getPackageManager (). QueryBroadcastReceivers (pushReceivedIntent, 0) .size () siempre es igual a 0.

Para esto no pase 0 en notify (), sino que pasa el valor "Calendar.getInstance (). GetTimeInMillis ()". Esto mostrará todas las notificaciones basadas en el tiempo.

Espero que esto te ayudará.

  • Descartar notificación actual en Acción pulsada
  • Anular el registro de un dispositivo de GCM mediante la identificación de registro en Android
  • GCM da un mensaje nulo
  • Notificaciones de usuarios - ¿Cómo recuperar un notification_id perdido de GCM?
  • ¿Cuál es la mejor manera de comunicarse entre las actividades del sitio web asp.net y la aplicación android?
  • Cómo hacer la notificación push desde el servidor al móvil Android
  • ID de registro duplicado de Android para diferentes dispositivos
  • No se puede obtener la notificación push desde el Dirigible Urbano
  • Notificación de emisión del receptor de difusión
  • ¿Cómo se juega un tono de timbre que es sólo para Push Notification Arrivals de mi aplicación?
  • Notificaciones push de Android con XMPP
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.