2012-09-24 32 views
13

He desarrollado una aplicación de notificación de inserción en Android de este tutorial: push notification in android app. El botón de registro se muestra cuando ejecuto la aplicación. Cuando hago clic en el botón de registro, y cuando el registro se realiza correctamente, aparece una notificación en mi dispositivo.Cómo agregar una notificación de inserción en mi propia aplicación de Android

¿Cómo puedo incluirlo en mi propia aplicación? Mi aplicación tiene una aplicación de ejemplo de análisis XML. Aquí, cuando se agrega un nuevo elemento, deseo mostrar (se muestra el nuevo pedido) un mensaje de notificación en el dispositivo. Se genera automáticamente aquí.

+2

C2DM está en desuso. Utilice https://developer.android.com/guide/google/gcm/index.html – gigadot

+0

bien, intentaré aprender y desarrollar el tutorial anterior – user1676640

+1

mi respuesta aquí: espero que ayude: http: // stackoverflow. com/a/12437549/554740 – HelmiB

Respuesta

17

Estoy publicando la aplicación de demostración de Google Cloud Messaging.

Asegúrese de crear aplicación de demostración con el nivel de la API igual o superior a sistema operativo Android 2.2 con Google API

usuario tiene que firmó en al-menos una cuenta de Google para utilizar este servicio.

Primero tienes que agregar GCM library.

que crear en la clase a la que llamé GCMIntentService que se extiende GCMBaseIntentService de la siguiente manera:

package com.example.gcmdemo; 

import android.content.Context; 
import android.content.Intent; 
import android.util.Log; 

import com.google.android.gcm.GCMBaseIntentService; 
import com.google.android.gcm.GCMConstants; 

public class GCMIntentService extends GCMBaseIntentService { 

    private static final String TAG = "Push Notification Demo GCMIntentService"; 

    @Override 
    protected void onError(Context context, String errorId) { 

     if(GCMConstants.ERROR_ACCOUNT_MISSING.equalsIgnoreCase(errorId)) { 
      Log.v(TAG, "Error Account Missing"); 
     } else if(GCMConstants.ERROR_AUTHENTICATION_FAILED.equalsIgnoreCase(errorId)) { 
      Log.v(TAG, "Error Authentication Failed"); 
     } else if(GCMConstants.ERROR_INVALID_PARAMETERS.equalsIgnoreCase(errorId)) { 
      Log.v(TAG, "Error Invalid Parameters"); 
     } else if(GCMConstants.ERROR_INVALID_SENDER.equalsIgnoreCase(errorId)) { 
      Log.v(TAG, "Error Invalid Sender"); 
     } else if(GCMConstants.ERROR_PHONE_REGISTRATION_ERROR.equalsIgnoreCase(errorId)) { 
      Log.v(TAG, "Error Phone Registration Error"); 
     } else if(GCMConstants.ERROR_SERVICE_NOT_AVAILABLE.equalsIgnoreCase(errorId)) { 
      Log.v(TAG, "Error Service Not Available"); 
     } 
    } 

    @Override 
    protected void onMessage(Context context, Intent intent) { 

     // App Server Sends message as key value pairs 
     String value1 = intent.getStringExtra("key1"); 
     String value2 = intent.getStringExtra("key2"); 

     Log.v(TAG, "key1: "+value1); 
     Log.v(TAG, "key2: "+value2); 
    } 

    @Override 
    protected void onRegistered(Context context, String regId) { 

     Log.v(TAG, "Successfull Registration : "+regId); 
    } 

    @Override 
    protected void onUnregistered(Context context, String regId) { 

     Log.v(TAG, "Successfully Unregistred : "+regId); 
    } 

    @Override 
    protected String[] getSenderIds(Context context) { 
     return super.getSenderIds(context); 
    } 

    @Override 
    protected void onDeletedMessages(Context context, int total) { 
     super.onDeletedMessages(context, total); 
    } 

    @Override 
    protected boolean onRecoverableError(Context context, String errorId) { 
     return super.onRecoverableError(context, errorId); 
    } 
} 

Aquí es cómo usted debe comprobar el registro en el seguimiento de la actividad de demostración:

package com.example.gcmdemo; 

import android.app.Activity; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.Menu; 

import com.google.android.gcm.GCMRegistrar; 

public class MainActivity extends Activity { 

    private static final String TAG = "Push Notification Demo Activity"; 
    private static final String SENDER_ID = "1069713227710"; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     GCMRegistrar.checkDevice(this); 
     GCMRegistrar.checkManifest(this); 
     final String regId = GCMRegistrar.getRegistrationId(this); 
     if (regId.equals("")) { 
      GCMRegistrar.register(this, SENDER_ID); 
     } else { 
      Log.v(TAG, "Already registered : "+regId); 
     } 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     getMenuInflater().inflate(R.menu.activity_main, menu); 
     return true; 
    } 
} 

Y, finalmente, el manifiesto de demostración:

<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.example.gcmdemo" 
    android:versionCode="1" 
    android:versionName="1.0" > 

    <uses-sdk 
     android:minSdkVersion="8" 
     android:targetSdkVersion="8" /> 

    <permission 
     android:name="com.example.gcmdemo.permission.C2D_MESSAGE" 
     android:protectionLevel="signature" /> 

    <uses-permission android:name="com.example.gcmdemo.permission.C2D_MESSAGE" /> 

    <!-- App receives GCM messages. --> 
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" /> 
    <!-- GCM connects to Google Services. --> 
    <uses-permission android:name="android.permission.INTERNET" /> 
    <!-- GCM requires a Google account. --> 
    <uses-permission android:name="android.permission.GET_ACCOUNTS" /> 
    <!-- Keeps the processor from sleeping when a message is received. --> 
    <uses-permission android:name="android.permission.WAKE_LOCK" /> 

    <application 
     android:icon="@drawable/ic_launcher" 
     android:label="@string/app_name" 
     android:theme="@style/AppTheme" > 
     <activity 
      android:name=".MainActivity" 
      android:label="@string/title_activity_main" > 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 

       <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 
     </activity> 

     <receiver 
      android:name="com.google.android.gcm.GCMBroadcastReceiver" 
      android:permission="com.google.android.c2dm.permission.SEND" > 
      <intent-filter> 
       <action android:name="com.google.android.c2dm.intent.RECEIVE" /> 
       <action android:name="com.google.android.c2dm.intent.REGISTRATION" /> 

       <category android:name="com.example.gcmdemo" /> 
      </intent-filter> 
     </receiver> 

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

</manifest> 

También se n eed third party server side script as specified here.

+0

ya he hecho los métodos anteriores.la aplicación se ejecutó correctamente y se muestra listview.i tengo que insertar un elemento en mi base de datos con éxito después de que voy a ver mi dispositivo no se muestra ningún mensaje de notificación en mi dispositivo. – user1676640

+0

¿limita la cantidad de notificaciones push en GCM? –

2

que sugieren personalmente que en lugar de GCM también hay otra biblioteca llamada Parse para PushNotification, funciona igual que Google mensajería en la nube, pero es tan tan tan tan mucho más fácil entonces GCM

Tienes que sólo tiene que descargar el archivo JAR y sencillo de dos de tres líneas de código para PUSH-NOTIFICACIÓN

para aprender utilizar este sitio https://parse.com/tutorials/android-push-notifications

Incluso usted no tiene que utilizar PHP o cualquier tipo de código del lado del servidor que proporciona las instalaciones que

mirada que da au demo

Parse.initialize(this, "YOUR_APP_ID", "YOUR_CLIENT_KEY"); 
    PushService.setDefaultPushCallback(this, YourDefaultActivity.class); 

desde arriba código es suficiente para recibir notificación de inserción

si quieres notificación envío que proporcionan interfaz de usuario agradable mirar la imagen de la interfaz de usuario que proporcionan

enter image description here

+1

Parse es una oferta comercial. ¿GCM tiene restricciones (precio) similares después de cierto límite? –

+0

parse es solo comercial en el modelo SaaS. también tienen la versión de código abierto de su servidor en github – kacper3w

2

envío de notificaciones push usando FCM

Google obsoleto el Google Cloud Messaging (GCM) y puso en marcha nuevo servidor de notificación de inserción que es Firebase mensajería en la nube (FCM). FCM es igual como GCM, FCM es también una solución de mensajería multiplataforma para plataformas móviles

Firebase mensajería en la nube puede enviar tres tipos de mensajes (Message types)

1.Notification Mensaje

2.Data mensaje

3.message tanto con notificación y datos

Firebase mensajería en la nube pasos integrador: -

1.Setup nuevo proyecto o proyecto de importación en Firbase consola (https://firebase.google.com/)

2.Add el mismo paquete de Nombre Aplicación en la aplicación Firebase.

3. Obtenga el archivo "google-services.json" y ponga ese archivo en la carpeta de la aplicación de su proyecto. Este archivo contiene todas las URL y las claves para el servicio de Google, así que no cambie ni edite este archivo.

4.Agregue nuevas dependencias de Gradle en Project for Firebase.

//app/build.gradle 
dependencies { 
    compile 'com.google.firebase:firebase-messaging:9.6.0' 
} 

apply plugin: 'com.google.gms.google-services' 

5. Cree una clase que contenga todos los valores constantes que usamos en la aplicación para FCM.

public class Config { 
public static final String TOPIC_GLOBAL = "global"; 
// broadcast receiver intent filters 
public static final String REGISTRATION_COMPLETE = "registrationComplete"; 
public static final String PUSH_NOTIFICATION = "pushNotification"; 

// id to handle the notification in the notification tray 
public static final int NOTIFICATION_ID = 100; 
public static final int NOTIFICATION_ID_BIG_IMAGE = 101; 
public static final String SHARED_PREF = "ah_firebase"; 
} 

6. Crear una clase llamada MyFirebaseInstanceIDService.java la que se recibe el ID de registro base de fuego que será única para cada aplicación. La identificación de registro se usa para enviar mensajes a un solo dispositivo.

public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService { 
    private static final String TAG = MyFirebaseInstanceIDService.class.getSimpleName(); 

    @Override 
    public void onTokenRefresh() { 
     super.onTokenRefresh(); 
     String refreshedToken = FirebaseInstanceId.getInstance().getToken(); 

     // Saving reg id to shared preferences 
     storeRegIdInPref(refreshedToken); 

     // sending reg id to your server 
     sendRegistrationToServer(refreshedToken); 

     // Notify UI that registration has completed, so the progress indicator can be hidden. 
     Intent registrationComplete = new Intent(Config.REGISTRATION_COMPLETE); 
     registrationComplete.putExtra("token", refreshedToken); 
     LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete); 
    } 

    private void sendRegistrationToServer(final String token) { 
     // sending gcm token to server 
     Log.e(TAG, "sendRegistrationToServer: " + token); 
    } 

    private void storeRegIdInPref(String token) { 
    SharedPreferences pref =  getApplicationContext().getSharedPreferences(Config.SHARED_PREF, 0); 
     SharedPreferences.Editor editor = pref.edit(); 
     editor.putString("regId", token); 
     editor.commit(); 
    } 
    } 

7.Cree una clase de servicio más llamada MyFirebaseMessagingService.java. Esto recibirá mensajes de firebase.

public class MyFirebaseMessagingService extends FirebaseMessagingService { 

    private static final String TAG = MyFirebaseMessagingService.class.getSimpleName(); 

    private NotificationUtils notificationUtils; 

    @Override 
    public void onMessageReceived(RemoteMessage remoteMessage) { 
     Log.e(TAG, "From: " + remoteMessage.getFrom()); 

     if (remoteMessage == null) 
      return; 

     // Check if message contains a notification payload. 
     if (remoteMessage.getNotification() != null) { 
      Log.e(TAG, "Notification Body: " + remoteMessage.getNotification().getBody()); 
      handleNotification(remoteMessage.getNotification().getBody()); 
     } 
    } 
private void handleNotification(String message) { 
     if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) { 
      // app is in foreground, broadcast the push message 
      Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION); 
      pushNotification.putExtra("message", message); 
      LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification); 

      // play notification sound 
      NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext()); 
      notificationUtils.playNotificationSound(); 
     }else{ 
      // If the app is in background, firebase itself handles the notification 
     } 
    } 
/** 
    * Showing notification with text only 
    */ 
    private void showNotificationMessage(Context context, String title, String message, String timeStamp, Intent intent) { 
     notificationUtils = new NotificationUtils(context); 
     intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); 
     notificationUtils.showNotificationMessage(title, message, timeStamp, intent); 
    } 

    /** 
    * Showing notification with text and image 
    */ 
    private void showNotificationMessageWithBigImage(Context context, String title, String message, String timeStamp, Intent intent, String imageUrl) { 
     notificationUtils = new NotificationUtils(context); 
     intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); 
     notificationUtils.showNotificationMessage(title, message, timeStamp, intent, imageUrl); 
    } 
} 

8.In la AndroidManifest.xml añadir estos dos servicios firebase MyFirebaseMessagingService y MyFirebaseInstanceIDService.

<!-- Firebase Notifications --> 
     <service android:name=".service.MyFirebaseMessagingService"> 
      <intent-filter> 
       <action android:name="com.google.firebase.MESSAGING_EVENT" /> 
      </intent-filter> 
     </service> 

     <service android:name=".service.MyFirebaseInstanceIDService"> 
      <intent-filter> 
       <action android:name="com.google.firebase.INSTANCE_ID_EVENT" /> 
      </intent-filter> 
     </service> 
     <!-- ./Firebase Notifications --> 

ahora simplemente Send your First Message

Notas:

* 1.Read el documento de Google para Firebase Cloud Messaging *

2. Si desea migrar una Aplicación de cliente GCM para Android a abeto ebase mensajería en la nube sigue estos pasos y Doc (Migrate a GCM Client App)

3.Android tutorial muestra y Código (Receive Reengagement Notifications)

Cuestiones relacionadas