2016-04-20 76 views
0

我正在嘗試使用GCM。我想從服務器(PHP文件)發送消息到我的設備(Android手機)使用GCM,沒有錯誤,但沒有收到消息

這個想法是啓動應用程序,加載任何導航器上的test.php(鉻,火狐......),然後應在我的手機上顯示通知。其實,我的手機沒有任何事情發生。在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(谷歌-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

  1. 登錄到您的谷歌Play開發者控制檯:看到你的谷歌Play開發者控制檯GCM統計,與應用程序的GCM簡單API密鑰或C2DM令牌通過以下步驟進行關聯。
  2. 選擇一個應用程序。
  3. 在左側菜單中,單擊服務& API
  4. 點擊鏈接發件人ID按鈕。
  5. 輸入您的GCM API密鑰或C2DM客戶端登錄令牌。
  6. Click Link

一旦你的應用發佈後,您可以將您的應用程序的統計頁面上查看GCM統計。

  1. 登錄到您的Google Play開發者控制檯。
  2. 選擇一個應用程序。
  3. 點擊左側菜單中的統計
  4. 在「統計信息」旁邊,點擊下拉菜單並選擇GCM統計信息

併爲您的編碼問題,這個SO後 - GCM couldnt receive message可以提供幫助。

相關問題