Notificaciones Push en la plataforma Android


Estoy buscando escribir una aplicación que reciba alertas enviadas desde un servidor. Encontré un par de métodos para hacer esto.

  1. SMS-Interceptar el SMS entrante e iniciar un pull desde el servidor
  2. Sondea el servidor periódicamente

Cada uno tiene sus propias limitaciones. SMS - no hay garantía a la hora de llegada. Poll puede drenar la batería.

¿Tienes una mejor sugerencia por favor? Muchas gracias.

Author: wonea, 2009-09-04

19 answers

Oficial de Google es la respuesta Android Cloud to Device Messaging Framework (obsoleto) Google Cloud Messaging(obsoleto) Firebase Cloud Messaging

Funcionará en Android >= 2.2 (en teléfonos que tienen Play Store).

 201
Author: BoD,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-29 03:14:20

(cross-posting de una respuesta que di a una pregunta similar - ¿Android admite notificaciones push casi en tiempo real? )

Recientemente empecé a jugar con MQTT http://mqtt.org para Android como una forma de hacer este tipo de cosas (es decir, notificaciones push que no son SMS sino datos, entrega de mensajes casi inmediata, no sondeo, etc.)

Tengo una entrada de blog con información de fondo sobre esto en caso de que sea útil

Http://dalelane.co.uk/blog/?p=938

(Nota: MQTT es una tecnología de IBM, y debo señalar que trabajo para IBM.)

 29
Author: dalelane,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:18:01

Android Cloud to Device Messaging Framework

Importante: C2DM ha sido oficialmente obsoleto a partir del 26 de junio de 2012. Esto significa que C2DM ha dejado de aceptar nuevos usuarios y solicitudes de cuotas. No se agregarán nuevas características a C2DM. Sin embargo, las aplicaciones que usan C2DM seguirán funcionando. Se anima a los desarrolladores de C2DM existentes a migrar a la nueva versión de C2DM, llamada Google Cloud Messaging para Android (GCM). Consulte el documento de migración de C2DM a GCM para obtener más información. Los desarrolladores deben usar GCM para el nuevo desarrollo.

Por favor revise el siguiente enlace:

Http://developer.android.com/guide/google/gcm/index.html

 17
Author: chiranjib,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-07-04 08:39:19

Aquí he escrito algunos pasos para Obtener RegID y Notificación a partir de cero

  1. Crear / Registrar aplicación en Google Cloud
  2. Configurar Cloud SDK con Desarrollo
  3. Configurar proyecto para GCM
  4. Obtener ID de registro del dispositivo
  5. Enviar notificaciones Push
  6. Recibir notificaciones Push

Puede encontrar el tutorial completo en el siguiente enlace URL

Primeros pasos con Android Push Notificación: Última nube de Google Mensajería (GCM) - tutorial completo paso a paso

introduzca la descripción de la imagen aquí

Recorte de código para obtener el ID de registro (Token de dispositivo para Notificaciones Push).

Configurar proyecto para GCM


Actualizar el archivo AndroidManifest

Para habilitar GCM en nuestro proyecto necesitamos agregar algunos permisos en nuestro archivo de manifiesto Ve a AndroidManifest.xml y añadir el siguiente código Añadir permiso

<uses-permission android:name="android.permission.INTERNET”/>
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />

<uses-permission android:name="android.permission.VIBRATE" />

<uses-permission android:name=“.permission.RECEIVE" />
<uses-permission android:name=“<your_package_name_here>.permission.C2D_MESSAGE" />
<permission android:name=“<your_package_name_here>.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />

Agregar Receptor de transmisión GCM declaración

Agregue la declaración del receptor de difusión GCM en su etiqueta de aplicación

<application
        <receiver
            android:name=".GcmBroadcastReceiver"
            android:permission="com.google.android.c2dm.permission.SEND" ]]>
            <intent-filter]]>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <category android:name="" />
            </intent-filter]]>

        </receiver]]>

<application/>

Add GCM Servie declaration

<application
     <service android:name=".GcmIntentService" />
<application/>

Obtener ID de registro (Token de dispositivo para Notificaciones Push)

Ahora Ve a tu Actividad de Lanzamiento/Splash

Agregar Constantes y Variables de Clase

private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
public static final String EXTRA_MESSAGE = "message";
public static final String PROPERTY_REG_ID = "registration_id";
private static final String PROPERTY_APP_VERSION = "appVersion";
private final static String TAG = "LaunchActivity";
protected String SENDER_ID = "Your_sender_id";
private GoogleCloudMessaging gcm =null;
private String regid = null;
private Context context= null;

Actualizar los métodos onCreate y onResume

@Override
protected void onCreate(Bundle savedInstanceState)
{
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_launch);
     context = getApplicationContext();
         if (checkPlayServices()) 
     {
            gcm = GoogleCloudMessaging.getInstance(this);
            regid = getRegistrationId(context);

            if (regid.isEmpty())
            {
                registerInBackground();
            }
            else
            {
            Log.d(TAG, "No valid Google Play Services APK found.");
            }
      }
 }

@Override protected void onResume()
{
       super.onResume();       checkPlayServices();
}


# Implement GCM Required methods (Add below methods in LaunchActivity)

private boolean checkPlayServices() {
        int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        if (resultCode != ConnectionResult.SUCCESS) {
            if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
                GooglePlayServicesUtil.getErrorDialog(resultCode, this,
                        PLAY_SERVICES_RESOLUTION_REQUEST).show();
            } else {
                Log.d(TAG, "This device is not supported - Google Play Services.");
                finish();
            }
            return false;
        }
        return true;
 }

private String getRegistrationId(Context context) 
{
   final SharedPreferences prefs = getGCMPreferences(context);
   String registrationId = prefs.getString(PROPERTY_REG_ID, "");
   if (registrationId.isEmpty()) {
       Log.d(TAG, "Registration ID not found.");
       return "";
   }
   int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
   int currentVersion = getAppVersion(context);
   if (registeredVersion != currentVersion) {
        Log.d(TAG, "App version changed.");
        return "";
    }
    return registrationId;
}

private SharedPreferences getGCMPreferences(Context context) 
{
    return getSharedPreferences(LaunchActivity.class.getSimpleName(),
                Context.MODE_PRIVATE);
}

private static int getAppVersion(Context context) 
{
     try 
     {
         PackageInfo packageInfo = context.getPackageManager()
                    .getPackageInfo(context.getPackageName(), 0);
            return packageInfo.versionCode;
      } 
      catch (NameNotFoundException e) 
      {
            throw new RuntimeException("Could not get package name: " + e);
      }
}


private void registerInBackground() 
{     new AsyncTask() {
     Override
     protected Object doInBackground(Object... params) 
     {
          String msg = "";
          try 
          {
               if (gcm == null) 
               {
                        gcm = GoogleCloudMessaging.getInstance(context);
               }
               regid = gcm.register(SENDER_ID);               Log.d(TAG, "########################################");
               Log.d(TAG, "Current Device's Registration ID is: "+msg);     
          } 
          catch (IOException ex) 
          {
              msg = "Error :" + ex.getMessage();
          }
          return null;
     }     protected void onPostExecute(Object result) 
     { //to do here };
  }.execute(null, null, null);
}

Nota : por favor almacene REGISTRATION_KEY, es importante para enviar el mensaje PN a GCM también mantener en la mina esto será único para todos los dispositivos, mediante el uso de este solo GCM enviará notificación Push.

Recibir notificaciones Push

Agregar GCM Broadcast Receiver Class

Como ya hemos declarado "GcmBroadcastReceiver.java " en nuestro archivo de manifiesto, así que vamos a crear esta clase actualizar el código de clase del receptor de esta manera

public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) 
    {        ComponentName comp = new ComponentName(context.getPackageName(),
                GcmIntentService.class.getName());        startWakefulService(context, (intent.setComponent(comp)));
        setResultCode(Activity.RESULT_OK);
        Toast.makeText(context, “wow!! received new push notification", Toast.LENGTH_LONG).show();
    }
}

Agregar Clase de servicio GCM

Como ya hemos declarado "GcmBroadcastReceiver.java " en nuestro archivo de manifiesto, así que vamos a crear esta clase actualizar el código de clase del receptor de esta manera

public class GcmIntentService extends IntentService
{     public static final int NOTIFICATION_ID = 1;     private NotificationManager mNotificationManager;     private final static String TAG = "GcmIntentService";     public GcmIntentService() {
     super("GcmIntentService");     
     }     @Override
     protected void onHandleIntent(Intent intent) {
          Bundle extras = intent.getExtras();
          Log.d(TAG, "Notification Data Json :" + extras.getString("message"));

          GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
          String messageType = gcm.getMessageType(intent);          if (!extras.isEmpty()) {          if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR
               .equals(messageType)) {
               sendNotification("Send error: " + extras.toString());
          } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED
          .equals(messageType)) {
          sendNotification("Deleted messages on server: "
          + extras.toString());          // If it's a regular GCM message, do some work.
          } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE
          .equals(messageType)) {
          // This loop represents the service doing some work.
          for (int i = 0; i < 5; i++) {
               Log.d(TAG," Working... " + (i + 1) + "/5 @ "
               + SystemClock.elapsedRealtime());               try {
                    Thread.sleep(5000);
               } catch (InterruptedException e) {
               }
             }
             Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());
             sendNotification(extras.getString("message"));
           }
        }        // Release the wake lock provided by the WakefulBroadcastReceiver.
        GcmBroadcastReceiver.completeWakefulIntent(intent);
     }     // Put the message into a notification and post it.
     // This is just one simple example of what you might choose to do with
     // a GCM message.
     private void sendNotification(String msg) {          mNotificationManager = (NotificationManager) this
          .getSystemService(Context.NOTIFICATION_SERVICE);
          PendingIntent contentIntent = PendingIntent.getActivity(this, 0,          new Intent(this, LaunchActivity.class), 0);

          NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(          this)
          .setSmallIcon(R.drawable.icon)
          .setContentTitle("Ocutag Snap")
          .setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
          .setContentText(msg)
          .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE);

          mBuilder.setContentIntent(contentIntent);          mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
     }
}
 17
Author: swiftBoy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-11-29 06:33:33

Mi comprensión / experiencia con las notificaciones push de Android son:

  1. C2DM GCM - Si tu plataforma Android objetivo es 2.2+, entonces ve por ella. Solo un truco, los usuarios de dispositivos tienen que estar siempre registrados con una cuenta de Google para obtener los mensajes.

  2. MQTT - Enfoque basado en Pub / Sub, necesita una conexión activa desde el dispositivo, puede agotar la batería si no se implementa sensiblemente.

  3. Deacon - Puede no ser bueno a largo plazo debido al apoyo limitado de la comunidad.

Edit : Añadido el 25 de noviembre de 2013

GCM - Google dice...

Para los dispositivos anteriores a la 3.0, esto requiere que los usuarios configuren su cuenta de Google en sus dispositivos móviles. Una cuenta de Google no es un requisito en dispositivos con Android 4.0.4 o superior.*

 17
Author: Lalit,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-02 10:22:38

Hay un nuevo esfuerzo de código abierto para desarrollar una biblioteca Java para notificaciones push en Android basada en el servidor web Meteor. Puedes comprobarlo en el Blog del Proyecto Deacon , donde encontrarás enlaces a Meteor y al repositorio GitHub del proyecto. Necesitamos desarrolladores, así que por favor corre la voz!

 11
Author: mtbkrdave,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-04-17 02:46:03

Puedes usar Xtify (http://developer.xtify.com ) - tienen un servicio web de notificaciones push que funciona con su SDK. es gratis y hasta ahora, ha funcionado muy bien para mí.

 9
Author: peter,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-03-18 22:47:32

O....

3) Mantenga una conexión con el servidor, envíe keep-alives cada pocos minutos, y el servidor puede enviar mensajes al instante. Así es como Gmail, Google Talk, etc. obrar.

 8
Author: Isaac Waller,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-09-04 22:20:32

Recomiendo usar GCM - Google Cloud Messaging para Android Es gratis, y para usos simples debe ser muy fácil.

Sin embargo, se requiere mantener un servidor de 3er lado para enviar las notificaciones en su nombre. Si quieres evitar que haya algunas soluciones industriales muy buenas para el servicio de notificaciones push de Android:

  • Urban Airship - notificaciones gratuitas de hasta 1 millón por mes, después se le cobrará por 1000 notificaciones
  • PushApps - gratis para notificaciones de 1M por mes, y notificaciones ilimitadas para 19.99 por mes
  • PushWoosh - gratis para dispositivos de 1M, los planes premium son de 39 EUROS

Diclaimer - Trabajo en PushApps y también uso su producto en mis aplicaciones desde hace más de un año.

 6
Author: Orr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-25 19:42:14

A partir del 18/05/2016 Firebase es la plataforma unificada de Google para desarrolladores móviles, incluidas las notificaciones push.

 6
Author: Freek Nortier,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-26 06:32:47

Me temo que ha encontrado ambos métodos posibles. Google, al menos inicialmente, iba a implementar una api de GChat que podría usar para una implementación push/pull. Lamentablemente, esa biblioteca fue cortada por Android 1.0.

 4
Author: haseman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-09-04 16:39:42

No sé si esto sigue siendo útil. Logré algo como esto con una biblioteca java en http://www.pushlets.com /

Aunque hacerlo en un servicio no evitará que Android lo apague y elimine el hilo de escucha.

 3
Author: n3utrino,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-10-20 20:48:30

Google C2DM está depreciado ahora, para eso, tiene o utilizar el nuevo servicio GCM (Google Cloud Messaging). Para la documentación, ver http://developer.android.com/guide/google/gcm/gs.html

 2
Author: Miloš,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-09-23 21:59:11

C2DM: los usuarios de la aplicación deben tener la cuenta de gmail.

MQTT: cuando su conexión llegue a 1024, dejará de funcionar porque usó "select model" de linux.

Hay un servicio push gratuito y api para Android, puedes probarlo: http://push-notification.org

 2
Author: Jacky,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-04 08:12:05

Método libre y fácil:

Si su base de usuarios objetivo no es grande(menos de 1000) y desea un servicio gratuito para comenzar, entonces Airbop es el mejor y más conveniente.

Sitio web de Airbop Utiliza el servicio de mensajería en la nube de Google a través de su API y proporciona un buen rendimiento. lo he utilizado para dos de mis proyectos y fue fácil de implementar.

Servicios como Urbanship y son excelentes, pero proporcionan una pila de implementación completa y no solo lo de las notificaciones push.

Si solo el servicio push es tu objetivo, Airbop funcionará bien.

No he usado Pushwoosh, pero también es una gran opción. Permite push a 1,000,000 dispositivos de forma gratuita

 2
Author: adimoh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-06-19 03:00:44

Sugeriría usar tanto SMS como HTTP. Si el usuario no ha iniciado sesión, envíe a su teléfono un SMS para notificarle que hay un mensaje en espera.

Así es como funciona este servicio de Ericsson Labs: https://labs.ericsson.com/apis/mobile-java-push /

Si implementa esto usted mismo, la parte difícil es eliminar los SMS entrantes sin que el usuario lo vea. O tal vez está bien si lo ven en tu caso.

Parece que esto funciona: Eliminar SMS Usando BroadcastReceiver - Android

Sí, escribir código como este puede ser peligroso y potencialmente puede arruinar la vida de alguien porque su aplicación eliminó un SMS que no debería haber.

 1
Author: Sarel Botha,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:47:24

Puedes usar Google Cloud Messaging o GCM, es gratis y fácil de usar. También puede utilizar servidores push de terceros como PushWoosh que le da más flexibilidad

 1
Author: Mohsen Afshin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-10 17:05:50

Hay muchos servidores de terceros como Urban Airship , Xtify, Mainline ,... lo cual permite enviar no solo en Android, sino también en iOS, Windows Phone ...

 1
Author: Panchine Lac,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-11 14:10:32

Puedes usar Empujador

Es un servicio alojado que hace que sea súper fácil agregar datos y funcionalidad en tiempo real a aplicaciones web y móviles.
Pusher ofrece bibliotecas para integrar en todos los tiempos de ejecución y frameworks principales.

PHP, Ruby, Python, Java, .NET, Go and Node en el servidor
JavaScript, Objective-C (iOS) and Java (Android) en el cliente.

 0
Author: Arash Hatami,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-14 17:55:04