我的gcm php服务器注册ID无效

时间:2015-01-23 18:23:59

标签: android google-cloud-messaging

所以我正在发布我的gcm.php并发送用户手机的注册ID,将其放入我服务器上的文本文件中(之后将实现数据库)。出于某种原因,当我发布到gcm服务器时,我收到了无效的注册错误。

我已经检查了我的txt文件并且它没有填充(这是问题)所以我很好奇我在我的Android客户端代码中没有与我的php服务器共享用户ID的错误。

gcm.php(服务器)

<?php


//generic php function to send GCM push notification
   function sendPushNotificationToGCM($registatoin_ids, $message) {
        //Google cloud messaging GCM-API url
        $url = 'https://android.googleapis.com/gcm/send';
        $fields = array(
            'registration_ids' => $registatoin_ids,
            'data' => $message,
        );
        // Google Cloud Messaging GCM API Key
        define("GOOGLE_API_KEY", "AIzaSyDA5dlLInMWVsJEUTIHV0u7maB82MCsZbU");        
        $headers = array(
            'Authorization: key=' . GOOGLE_API_KEY,
            'Content-Type: application/json'
        );
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);   
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
        $result = curl_exec($ch);               
        if ($result === FALSE) {
            die('Curl failed: ' . curl_error($ch));
        }
        curl_close($ch);
        return $result;
    }
?>
<?php

    //this block is to post message to GCM on-click
    $pushStatus = "";   
    if(!empty($_GET["push"])) { 
        $gcmRegID  = file_get_contents("GCMRegId.txt");
        $pushMessage = $_POST["message"];   
        if (isset($gcmRegID) && isset($pushMessage)) {      
            $gcmRegIds = array($gcmRegID);
            $message = array("m" => $pushMessage);  
            $pushStatus = sendPushNotificationToGCM($gcmRegIds, $message);
        }       
    }

    //this block is to receive the GCM regId from external (mobile apps)
    if(!empty($_GET["shareRegId"])) {
        $gcmRegID  = $_POST["regId"]; 
        file_put_contents("GCMRegId.txt",$gcmRegID);
        echo "Ok!";
        exit;
    }   
?>
<html>
    <head>
        <title>Google Cloud Messaging (GCM) Server in PHP</title>
    </head>
    <body>
        <h1>Google Cloud Messaging (GCM) Server in PHP</h1> 
        <form method="post" action="gcm.php/?push=1">                                                
            <div>                                
                <textarea rows="2" name="message" cols="23" placeholder="Message to transmit via GCM"></textarea>
            </div>
            <div><input type="submit"  value="Send Push Notification via GCM" /></div>
        </form>
        <p><h3><?php echo $pushStatus; ?></h3></p>        
    </body>
</html>

这是android客户端(我尝试与服务器共享regId) MainActivity.java

 class GcmRegistrationAsyncTask extends AsyncTask<Void, Void, String> {

    private GoogleCloudMessaging gcm;
    private Context context;

    // TODO: change to your own sender ID to Google Developers Console project number, as per instructions above
    private static final String SENDER_ID = "617516375608";

    public GcmRegistrationAsyncTask(Context context) {
        this.context = context;
    }

    @Override
    protected String doInBackground(Void... params) {
        if (regService == null) {
            Registration.Builder builder = new Registration.Builder(AndroidHttp.newCompatibleTransport(), new AndroidJsonFactory(), null)
                    .setRootUrl("https://keen-proton-827.appspot.com/_ah/api/");
            // end of optional local run code

            regService = builder.build();
        }

        String msg = "";
        try {
            if (gcm == null) {
                gcm = GoogleCloudMessaging.getInstance(context);
            }
            String regId = gcm.register(SENDER_ID);
            msg = "Device registered, registration ID=" + regId;

            // You should send the registration ID to your server over HTTP,
            // so it can use GCM/HTTP or CCS to send messages to your app.
            // The request to your server should be authenticated if your app
            // is using accounts.


            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost("http://68.84.84.84/gcm.php?shareRegId=1");

            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("regId", regId));
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            HttpResponse response = httpClient.execute(httpPost);

            Log.d("STATUS", response.toString());

            regService.register(regId).execute();

        } catch (IOException ex) {
            ex.printStackTrace();
            msg = "Error: " + ex.getMessage();
        }
        return msg;
    }

    @Override
    protected void onPostExecute(String msg) {
        Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
        Logger.getLogger("REGISTRATION").log(Level.INFO, msg);
    }
}

1 个答案:

答案 0 :(得分:0)

注册ID:在Android客户端中成功注册后获得的令牌

String token =
                            InstanceID.getInstance(mContext).getToken(senderId,
                                    GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);