2012-09-24 22 views
13

Ho sviluppato un'applicazione di notifica push in Android da questo tutorial: push notification in android app. Il pulsante di registrazione viene visualizzato quando eseguo l'app. Quando faccio clic sul pulsante di registrazione e quando la registrazione ha esito positivo, sul mio dispositivo viene visualizzata una notifica.Come aggiungere una notifica push nella mia app Android

Come posso includerlo nella mia app? La mia app ha un'app di esempio di analisi xml. Qui quando viene aggiunto un nuovo elemento, desidero visualizzare (il nuovo ordine è visualizzato) un messaggio di notifica sul dispositivo. Viene generato automaticamente qui.

+2

C2DM è deprecato. Si prega di utilizzare https://developer.android.com/guide/google/gcm/index.html – gigadot

+0

ok cercherò di imparare e sviluppare il tutorial sopra – user1676640

+1

aspetto della mia risposta qui: spero che aiuti: http: // StackOverflow. com/a/12437549/554740 – HelmiB

risposta

17

Sto postando un'applicazione dimostrativa di Google Cloud Messaging.

Assicurarsi di creare applicazioni demo con livello di API uguale o superiore a sistema operativo Android 2.2 con Google API

utente deve firmato a at-almeno un account Google per utilizzare questo servizio.

Per prima cosa è necessario aggiungere GCM library.

che creare in classe che ho chiamato GCMIntentService che si estende GCMBaseIntentService come segue:

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); 
    } 
} 

Ecco come si dovrebbe verificare iscrizione nel seguente attività demo:

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; 
    } 
} 

E infine il manifesto demo:

<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> 

Anche tu n eed third party server side script as specified here.

+0

ya ho fatto sopra i metodi. L'app è stata eseguita correttamente e visualizzato listview.i devo inserire un elemento nel mio database con successo dopo che andrò a vedere il mio dispositivo nessun messaggio di notifica è visualizzato sul mio dispositivo. – user1676640

+0

limitare la quantità di notifiche push in GCM? –

2

personalmente suggeriscono che invece di GCM c'è anche altro libreria denominata Parse per PushNotification, funziona stessa di Google Cloud Messaging ma è così così così tanto facile allora GCM

Devi scaricare solo file JAR e semplice linea due-tre di codice per PUSH-NOTIFICA

per imparare utilizzare questo sito https://parse.com/tutorials/android-push-notifications

Anche nota bene: non è necessario utilizzare PHP o qualsiasi tipo di codice lato server, fornire struttura

012.

sguardo darò u demo

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

dall'alto codice è sufficiente per ricevere notifica push

se si desidera la notifica invio forniscono piacevole interfaccia utente osservi l'immagine di interfaccia utente che forniscono

enter image description here

+1

Parse è un'offerta commerciale. GCM ha restrizioni simili (prezzo) dopo un certo limite? L'analisi –

+0

è solo commerciale nel modello SaaS. hanno anche la versione open source del loro server su github – kacper3w

2

Invio Push Notification utilizzando FCM

Google deprecato il Google Cloud Messaging (GCM) e ha lanciato nuovo server di notifica push che è Firebase Nuvola Messaging (FCM). FCM è lo stesso come il MCG, FCM è anche una soluzione di messaggistica cross-platform per piattaforme mobili

Firebase cloud di messaggistica in grado di inviare tre tipi di messaggi (Message types)

1.Notification Messaggio

2.Data Messaggio

3.message sia con notifica e Data

0.123.

Firebase Cloud Messaging passi Integrazione: -

1.IMPOSTA Nuovo progetto o un progetto di importazione in Firbase Console (https://firebase.google.com/)

2.Add lo stesso nome del pacchetto di App in Firebase App.

3. Ottieni il file "google-services.json" e metti il ​​file nella cartella dell'app del progetto. Questo file contiene tutti gli Url e le Chiavi per il servizio di Google, quindi non modificare o modificare questo file.

4.Aggiungi nuove dipendenze Gradle in Project for Firebase.

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

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

5.Crea una classe che contiene tutti i valori costanti che usiamo nell'app per 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. Creare una classe denominata MyFirebaseInstanceIDService.java che sarà riceve l'ID di registrazione Firebase che sarà unico per ogni app. L'ID di registrazione viene utilizzato per inviare un messaggio a un singolo 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.Creare un'altra classe di servizio denominata MyFirebaseMessagingService.java. Questo riceverà messaggi 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 l'AndroidManifest.xml aggiungere questi due servizi Firebase MyFirebaseMessagingService e 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 --> 

ora semplicemente Send your First Message

Note:

* 1.Read il Doc di Google per Firebase Cloud Messaging *

2. Se si desidera migrare un App Client GCM per Android a Fir ebase cloud Messaging attenersi alla seguente procedura e Doc (Migrate a GCM Client App)

3.Android esercitazione di esempio e il codice (Receive Reengagement Notifications)