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:
- Validación de Token GCM
- Notificación push de C2DM sin MQTT, UA en android api level <8
- Notificación de 10 días de la infracción a término de desarrollador de Google Play con respecto al servicio de notificación push de OneSignal
- Mensaje de emisión extraño recibido en el inicio de la aplicación
- Problema de registro del dispositivo Gcm en android
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?
- El emulador de Android no recibe notificaciones push
- Cómo verificar el ID del remitente de GCM de deviceToken en Parse.com
- Push notificación de UrbanAirship no funciona con servidor en vivo (es decir, con la clave de producción) en android
- Error de GCM - googleCloudMessaging.register
- ¿Qué puerto y protocolo utiliza Google Cloud Messaging (GCM)?
- Android, enviar mensajes a 1000 dispositivos rápidamente
- Android "hola mundo" ejemplo pushnotification
- Android push notificación a muchos dispositivos a la vez usando google c2dm
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á.
- Se ha producido un error al establecer la orientación
- Cómo pasar de una pantalla a la siguiente con animación