2016-04-20 2 views
0

Я пытаюсь использовать GCM. Я хочу отправить сообщение с сервера (файл PHP) на мое устройство (телефон Android)Использование GCM, без ошибок, но не получено сообщение

Идея - запустить приложение, загрузить test.php на любой навигатор (хром, firefox ...), а затем на моем телефоне должно появиться уведомление. На самом деле на моем телефоне ничего не происходит. В журнале Android Studio я могу видеть маркер регистрации GCM, так что все в порядке. Но после ... Я немного потерял. Как я могу проверить сообщение отправлено на сервер? Как я могу узнать, что служба прослушивает приложение?

Вот мои фактические файлы, у меня нет ошибки, когда я отправить сообщение, и когда я запустить приложение:

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 (я удалил ключ API от здесь)

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

И для приложения:

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 генерируется и находится в "приложение" папку)

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' 

и, наконец, манифест

<uses-permission android:name="android.permission.INTERNET" /> 
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 
    <!-- [START gcm_permission] --> 
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" /> 
    <uses-permission android:name="android.permission.WAKE_LOCK" /> 
<service 
      android:name=".MyGcmListenerService" 
      android:exported="false"> 
      <intent-filter> 
       <action android:name="com.google.android.c2dm.intent.RECEIVE"/> 
      </intent-filter> 
     </service> 
     <service 
      android:name=".MyInstanceIDListenerService" 
      android:exported="false"> 
      <intent-filter> 
       <action android:name="com.google.android.gms.iid.InstanceID"/> 
      </intent-filter> 
     </service> 
     <service 
      android:name=".RegistrationIntentService" 
      android:exported="false"> 
     </service> 
+0

Добро пожаловать в StackOverflow. Пожалуйста, отредактируйте свой вопрос со спецификой того, что не так с вашим текущим кодом и тем, что вы ожидаете. – buczek

+0

Отредактировано, спасибо. – Neo

ответ

0

Просмотр статуса сообщений, отправленных через GCM, теперь доступен для опубликованных приложений Google Play с помощью GCM statistics. Для просмотра статистики GCM на вашей консоли разработчика Google Play, ассоциируют GCM Простой ключ API или маркер C2DM с приложением следующие шаги:

  1. Войдите в свой Google Play Developer Console.
  2. Выберите приложение.
  3. В меню слева нажмите Услуги & API.
  4. Нажмите Ссылка на источник ID кнопка.
  5. Введите свой ключ API GCM или токен входа в систему C2DM.
  6. Нажмите Ссылка.

После того, как ваше приложение будет опубликовано, вы можете просмотреть статистику GCM на Статистика страницы вашего приложения.

  1. Войдите в свою консоль разработчика Google Play.
  2. Выберите приложение.
  3. В левом меню нажмите Статистика.
  4. Рядом с "Статистика", щелкните мышью на выпадающем и выберите GCM статистика.

И для кодирования проблемы, это SO пост - GCM couldnt receive message может помочь.

Смежные вопросы