2015-01-23 3 views
0

그래서 내 gcm.php에 게시하고 사용자 전화의 등록 ID를 내 서버의 텍스트 파일에 넣으려고합니다 (나중에 DB를 구현합니다). 어떤 이유로 gcm 서버에 게시 할 때 잘못된 등록 오류가 발생합니다.내 gcm PHP 서버가 잘못된 등록 ID

내 txt 파일을 검사했는데 채워지지 않았습니다. (문제가 있습니다) 그래서 내 안드로이드 클라이언트 측 코드에서 내 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> 

그리고 내가 서버 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); 
    } 
} 
+0

질문에 정확하게 답변하지는 않지만 https://github.com/unmultimedio/gcm_server_php 백엔드 GCM 구현 (PHP도)을 확인하고 API 키를 공개하지 마십시오. – unmultimedio

+0

예, Android 클라이언트 측에서 공유하는 방법을 알아야합니다. 내 PHP 스크립트 올바르게 POST를 처리하는지 잘 모르겠지만, 그렇게 생각합니다. 그리고이 API 키는 튜토리얼에서 나온 것입니다 :) – cj1098

답변

0

등록 ID로 REGID을 공유하려고 안드로이드 클라이언트 (이다 : 토큰 Android 클라이언트에 성공적으로 등록 된 후

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