2016-04-20 4 views
0

Ich versuche, GCM zu verwenden. Ich möchte eine Nachricht von einem Server (PHP-Datei) an mein Gerät (Android-Handy) sendenMit GCM, kein Fehler, aber keine Nachricht erhalten

Die Idee ist, die App zu starten, laden Sie test.php auf jedem Navigator (Chrome, Firefox ...) und dann Eine Benachrichtigung sollte auf meinem Telefon erscheinen. Eigentlich passiert nichts auf meinem Handy. Im Log von Android Studio kann ich das GCM-Registrierungs-Token sehen, also ist es in Ordnung. Aber nach ... bin ich ein wenig verloren. Wie kann ich überprüfen, ob die Nachricht an den Server gesendet wird? Wie kann ich wissen, dass der Dienst eine App abhört?

Hier ist meine aktuellen Dateien, ich habe keinen Fehler, wenn ich die Nachricht zu senden, und wenn ich die app starten:

test.php

<?php 

ini_set('display_errors', 1); 
ini_set('display_startup_errors', 1); 
error_reporting(E_ALL); 

require_once __DIR__ . '/gcm.php'; 

$gcm = new GCM(); 

$data = array(); 
$data['message'] = "Un message de test"; 

// the topic you want to send notification 
$topic = 'global'; 

// sending push message to a topic 
$gcm->sendToTopic($topic, $data); 

?> 

gcm.php (Ich habe den API-Schlüssel entfernt von hier)

<?php 
class GCM { 

    // constructor 
    function __construct() { 

    } 

    // sending push message to single user by gcm registration id 
    public function send($to, $message) { 
     $fields = array(
      'to' => $to, 
      'data' => $message, 
     ); 
     return $this->sendPushNotification($fields); 
    } 

    // Sending message to a topic by topic id 
    public function sendToTopic($to, $message) { 
     $fields = array(
      'to' => '/topics/' . $to, 
      'data' => $message, 
     ); 
     return $this->sendPushNotification($fields); 
    } 

    // sending push message to multiple users by gcm registration ids 
    public function sendMultiple($registration_ids, $message) { 
     $fields = array(
      'registration_ids' => $registration_ids, 
      'data' => $message, 
     ); 

     return $this->sendPushNotification($fields); 
    } 

    // function makes curl request to gcm servers 
    private function sendPushNotification($fields) { 

     // include config 

     // Set POST variables 
     $url = 'https://gcm-http.googleapis.com/gcm/send'; 

     $headers = array(
      'Authorization: key=AIz...', 
      'Content-Type: application/json' 
     ); 
     // Open connection 
     $ch = curl_init(); 

    // Set the url, number of POST vars, POST data 
    curl_setopt($ch, CURLOPT_URL, $url); 

    curl_setopt($ch, CURLOPT_POST, true); 
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 

    // Disabling SSL Certificate support temporarly 
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 

    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields)); 

    // Execute post 
    $result = curl_exec($ch); 
    if ($result === FALSE) { 
     die('Curl failed: ' . curl_error($ch)); 
    } 

    // Close connection 
    curl_close($ch); 

    return $result; 
}}?> 

Und für die App:

MainActivity.java

protected void onCreate(Bundle savedInstanceState) { 
super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     // Registering BroadcastReceiver 
     //registerReceiver(); 

     if (checkPlayServices()) { 
      // Start IntentService to register this application with GCM. 
      Intent intent = new Intent(this, RegistrationIntentService.class); 
      startService(intent); 

     } 
... 
private boolean checkPlayServices() { 
     GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance(); 
     int resultCode = apiAvailability.isGooglePlayServicesAvailable(this); 
     if (resultCode != ConnectionResult.SUCCESS) { 
      if (apiAvailability.isUserResolvableError(resultCode)) { 
       apiAvailability.getErrorDialog(this, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST) 
         .show(); 
      } else { 
       Log.i(TAG, "This device is not supported."); 
       finish(); 
      } 
      return false; 
     } 
     return true; 
    } 

RegistrationIntentService.java

public class RegistrationIntentService extends IntentService { 

    private static final String TAG = "RegIntentService"; 
    private static final String[] TOPICS = {"global"}; 

    public RegistrationIntentService() { 
     super(TAG); 
    } 

    @Override 
    protected void onHandleIntent(Intent intent) { 
     SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); 

     try { 
      InstanceID instanceID = InstanceID.getInstance(this); 
      String token = instanceID.getToken(getString(R.string.gcm_defaultSenderId), 
        GoogleCloudMessaging.INSTANCE_ID_SCOPE, null); 
      Log.i(TAG, "GCM Registration Token: " + token); 


      sendRegistrationToServer(token); 

      subscribeTopics(token); 
     sharedPreferences.edit().putBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, true).apply(); 

     } catch (Exception e) { 
      Log.d(TAG, "Failed to complete token refresh", e); 

      sharedPreferences.edit().putBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, false).apply(); 
     } 
    } 

    /** 
    * Persist registration to third-party servers. 
    * 
    * Modify this method to associate the user's GCM registration token with any server-side account 
    * maintained by your application. 
    * 
    * @param token The new token. 
    */ 
    private void sendRegistrationToServer(String token) { 
     // Add custom implementation, as needed. 
    } 

    /** 
    * Subscribe to any GCM topics of interest, as defined by the TOPICS constant. 
    * 
    * @param token GCM token 
    * @throws IOException if unable to reach the GCM PubSub service 
    */ 
    // [START subscribe_topics] 
    private void subscribeTopics(String token) throws IOException { 
     GcmPubSub pubSub = GcmPubSub.getInstance(this); 
     for (String topic : TOPICS) { 
      pubSub.subscribe(token, "/topics/" + topic, null); 
     } 
    } 
    // [END subscribe_topics] 

} 

MyGcmListenerService.java

import android.app.NotificationManager; 
import android.app.PendingIntent; 
import android.content.Context; 
import android.content.Intent; 
import android.media.RingtoneManager; 
import android.net.Uri; 
import android.os.Bundle; 
import android.support.v4.app.NotificationCompat; 
import android.util.Log; 

import com.google.android.gms.gcm.GcmListenerService; 

public class MyGcmListenerService extends GcmListenerService { 

    private static final String TAG = "MyGcmListenerService"; 

    /** 
    * Called when message is received. 
    * 
    * @param from SenderID of the sender. 
    * @param data Data bundle containing message data as key/value pairs. 
    *    For Set of keys use data.keySet(). 
    */ 
    // [START receive_message] 
    @Override 
    public void onMessageReceived(String from, Bundle data) { 
     String message = data.getString("message"); 
     Log.d(TAG, "From: " + from); 
     Log.d(TAG, "Message: " + message); 

     if (from.startsWith("/topics/")) { 
      // message received from some topic. 
     } else { 
      // normal downstream message. 
     } 

     // [START_EXCLUDE] 
     /** 
     * Production applications would usually process the message here. 
     * Eg: - Syncing with server. 
     *  - Store message in local database. 
     *  - Update UI. 
     */ 

     /** 
     * In some cases it may be useful to show a notification indicating to the user 
     * that a message was received. 
     */ 
     sendNotification(message); 
     // [END_EXCLUDE] 
    } 
    // [END receive_message] 

    /** 
    * Create and show a simple notification containing the received GCM message. 
    * 
    * @param message GCM message received. 
    */ 
    private void sendNotification(String message) { 
     Intent intent = new Intent(this, MainActivity.class); 
     intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
     PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent, 
       PendingIntent.FLAG_ONE_SHOT); 

     Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); 
     NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this) 
       .setSmallIcon(R.drawable.notification_icon) 
       .setContentTitle("GCM Message") 
       .setContentText(message) 
       .setAutoCancel(true) 
       .setSound(defaultSoundUri) 
       .setContentIntent(pendingIntent); 

     NotificationManager notificationManager = 
       (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 

     notificationManager.notify(1 /* ID of notification */, notificationBuilder.build()); 
    } 
} 

build.gradle (Google-services.json erzeugt wird, und ist in "app" -Ordner)

dependencies { 
    compile fileTree(include: ['*.jar'], dir: 'libs') 
    testCompile 'junit:junit:4.12' 
    compile 'com.android.support:appcompat-v7:23.1.1' 
    compile 'com.android.support:design:23.1.1' 
    compile 'com.google.android.gms:play-services-appindexing:8.4.0' 
    compile 'com.google.android.gms:play-services:8.4.0' 
} 

buildscript { 
    repositories { 
     jcenter() 
    } 
    dependencies { 
     // Google Play Services 
     classpath 'com.google.gms:google-services:1.3.0-beta1' 
    } 
} 
apply plugin: 'com.google.gms.google-services' 

und schließlich das Manifest

+0

Willkommen bei StackOverflow. Bitte bearbeiten Sie Ihre Frage mit Informationen darüber, was mit Ihrem aktuellen Code nicht stimmt und was Sie erwarten. – buczek

+0

Editiert, danke. – Neo

Antwort

0

Das Anzeigen des Status von Nachrichten, die über GCM gesendet werden, ist jetzt für veröffentlichte Google Play-Apps mit GCM statistics verfügbar. Um GCM Statistiken über Ihre Google Play Developer Console, assoziieren die GCM Simple API Key oder C2DM Token mit Ihrer Anwendung durch die folgenden Schritte zu sehen:

  1. Melden Sie sich in Ihrer Google Play Developer Console.
  2. Wählen Sie eine App aus.
  3. Klicken Sie im linken Menü auf Services & APIs.
  4. Klicken Sie auf die Verknüpfen Sie eine Absender-ID Schaltfläche.
  5. Geben Sie Ihren GCM-API-Schlüssel oder das C2DM-Client-Login-Token ein.
  6. Klicken Sie auf Link.

Sobald Ihre App veröffentlicht wird, können Sie GCM Statistiken Ihrer App sehen Statistiken Seite.

  1. Melden Sie sich in Ihrer Google Play Developer Console.
  2. Wählen Sie eine App aus. Klicken Sie im Menü links auf Statistik.
  3. Klicken Sie neben "Statistics" auf das Drop-down-Menü und wählen Sie GCM statistics.

Und für Ihre Codierung Problem, das SO Post - GCM couldnt receive message kann helfen.

Verwandte Themen