2012-06-14 60 views
0

我已經編碼的ac2dm應用程序,我跟着this教程,C2DM PushDemo問

但是...我發現代碼一些奇怪......這裏的代碼..

package de.vogella.android.c2dm.simpleclient; 

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.util.ArrayList; 
import java.util.List; 

import org.apache.http.HttpResponse; 
import org.apache.http.NameValuePair; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.entity.UrlEncodedFormEntity; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.message.BasicNameValuePair; 

import android.app.Notification; 
import android.app.NotificationManager; 
import android.app.PendingIntent; 
import android.content.BroadcastReceiver; 
import android.content.Context; 
import android.content.Intent; 
import android.content.SharedPreferences; 
import android.content.SharedPreferences.Editor; 
import android.preference.PreferenceManager; 
import android.provider.Settings.Secure; 
import android.util.Log; 

public class C2DMRegistrationReceiver extends BroadcastReceiver { 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     String action = intent.getAction(); 
     Log.w("C2DM", "Registration Receiver called"); 
     if ("com.google.android.c2dm.intent.REGISTRATION".equals(action)) { 
      Log.w("C2DM", "Received registration ID"); 
      final String registrationId = intent 
        .getStringExtra("registration_id"); 
      String error = intent.getStringExtra("error"); 

      Log.d("C2DM", "dmControl: registrationId = " + registrationId 
        + ", error = " + error); 
      String deviceId = Secure.getString(context.getContentResolver(), 
        Secure.ANDROID_ID); 
      createNotification(context, registrationId); 
      sendRegistrationIdToServer(deviceId, registrationId); 
      // Also save it in the preference to be able to show it later 
      saveRegistrationId(context, registrationId); 
     } 
    } 

    private void saveRegistrationId(Context context, String registrationId) { 
     SharedPreferences prefs = PreferenceManager 
       .getDefaultSharedPreferences(context); 
     Editor edit = prefs.edit(); 
     edit.putString(C2DMClientActivity.AUTH, registrationId); 
     edit.commit(); 
    } 

    public void createNotification(Context context, String registrationId) { 
     NotificationManager notificationManager = (NotificationManager) context 
       .getSystemService(Context.NOTIFICATION_SERVICE); 
     Notification notification = new Notification(R.drawable.icon, 
       "Registration successful", System.currentTimeMillis()); 
     // Hide the notification after its selected 
     notification.flags |= Notification.FLAG_AUTO_CANCEL; 

     Intent intent = new Intent(context, RegistrationResultActivity.class); 
     intent.putExtra("registration_id", registrationId); 
     PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, 
       intent, 0); 
     notification.setLatestEventInfo(context, "Registration", 
       "Successfully registered", pendingIntent); 
     notificationManager.notify(0, notification); 
    } 

    // Incorrect usage as the receiver may be canceled at any time 
    // do this in an service and in an own thread 
    public void sendRegistrationIdToServer(String deviceId, 
      String registrationId) { 
     Log.d("C2DM", "Sending registration ID to my application server"); 
     HttpClient client = new DefaultHttpClient(); 
     **HttpPost post = new HttpPost("http://vogellac2dm.appspot.com/register");** 
     try { 
      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); 
      // Get the deviceID 
      nameValuePairs.add(new BasicNameValuePair("deviceid", deviceId)); 
      nameValuePairs.add(new BasicNameValuePair("registrationid", 
        registrationId)); 

      post.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
      HttpResponse response = client.execute(post); 
      BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); 

      String line = ""; 
      while ((line = rd.readLine()) != null) { 
       Log.e("HttpResponse", line); 
      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

看這個pary HttpPost post = new HttpPost(「http://vogellac2dm.appspot.com/register」);

爲什麼我必須在這裏發送數據?有誰知道?因爲當我試圖訪問它,我發現該鏈接已經死了......

感謝======================= =========== 嘿...我已經解決了它...但現在我得到新的麻煩......我得到內容的麻煩......當我嘗試從我的PHP發送它,我得到這樣

Warning: strlen() expects parameter 1 to be string, array given in /home/k8665578/public_html/android/c2dm/send_notification.php on line 66 

這是一個警告的PHP代碼...

<?php 
     $host   =  'localhost'; 
     $user   =  'k8xxx_kiosban'; 
     $pass   =  'k8xxx'; 
     $database  =  'k8k8xxx_kiosban'; 
     $username ="[email protected]"; 
     $password = "xxxxiba"; 
     $source="My-Server-Event-Alerter"; //anything that says about ur app 
     $service="ac2dm"; 

     $connection = mysql_connect ($host, $user, $pass) or die      ('Error connecting to mysql'.mysql_error()); 
       //mysql_select_db ($database,$connection)or die      ('Error selecting database '.mysql_error()); 

      mysql_selectdb($database) or die ('->>Error selecting database'.mysql_error()); 
       if ($_GET [ 'message' ] != '') 
       { 
         $message =$_GET ['message']; 
         echo 'Message sent to server '.$message; 

      $post_params = array ("Email" => $username, "Passwd" => $password, "accountType"=>"GOOGLE", "source" => $source, "service"=>$service); 

      $first = true; 
      $data_msg = ""; 

      foreach ($post_params as $key => $value) { 
      if ($first) 
       $first = false; 
      else 
       $data_msg .= "&"; 

      $data_msg .= urlencode($key) ."=". urlencode($value); 
      } 

      $x = curl_init("https://www.google.com/accounts/ClientLogin"); 

      curl_setopt($x, CURLOPT_HEADER, 1); 
      curl_setopt($x, CURLOPT_POST, 1); 
      curl_setopt($x, CURLOPT_POSTFIELDS, $data_msg); 
      curl_setopt($x, CURLOPT_RETURNTRANSFER, 1); 
      $response = curl_exec($x); 
      curl_close($x); 

      echo $response; 

      $pos = strpos($response, "Auth="); 
      $authKey = trim(substr($response, 5+$pos)); 

      $result=mysql_query("SELECT * FROM android_devices"); 
         if(mysql_num_rows($result)>0){ 
           $sucess= 'Message sent to '.mysql_num_rows($result).' devices'; 
           $row = mysql_fetch_assoc ($result); 

           do { 
             $deviceToken = $row['devicetoken']; 
             echo 'Device Token:'.$deviceToken . ''; 
             $data = array(
             'registration_id' => $deviceToken, 
             'collapse_key' => 'ck_' . 'col_key', 
             'data.message' => $message, 
             'data.title' =>'Requestec Push Demo'); 

             //$data = (is_array($data)) ? http_build_query($data) : $data; 

             $ch = curl_init(); 

             curl_setopt($ch, CURLOPT_URL, "https://android.apis.google.com/c2dm/send"); 
             echo 'Content-Length:'.strlen($data); 
             $headers = array('Authorization: GoogleLogin auth=' . $authKey/*,'Content-Length:'.strlen($data)*/); 
             if($headers){ 
              curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); 
             } 
             curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); 
             curl_setopt($ch, CURLOPT_POST, true); 
             curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
             curl_setopt($ch, CURLOPT_POSTFIELDS, $data); 

             $messagedata = curl_exec($ch); 
             echo $messagedata; 
             curl_close($ch); 
        }while($row = mysql_fetch_assoc ($result)); 
       } 
      } 
?> 

Push Notification 

<form action="./send_notification.php" method="get" enctype="application/x-www-form-urlencoded" name="Send Notification" target="_self"> 
<label>Push Message 
<input name="message" type="text" size="50" maxlength="50"></label> 
<input name="Send Message" type="submit" value="Send Message"> 
</form> 

<?php $sucess;?> 

而且然後,當我嘗試發送時,我收到通知,但有時內容與我發送的內容不相同...

例如,首先發送一條消息「Tes percobaan」,在我的設備上,我收到「Tes percobaan 「,但如果我再次發送一條消息」percobaaan「,我收到我的設備上的通知,但內容是」Tes percobaan「< -

之前的內容

有沒有什麼建議?

回答

0

您複製的示例代碼使用了您關注的線即將註冊ID發回一些服務器進行存儲。在大多數情況下,這將發送到您自己的應用程序服務器,以便您可以存儲設備的註冊ID並在以後使用它將C2DM數據發送到設備。

由於在發送數據之前您需要知道設備的註冊ID,只需將該URL替換爲您的應用程序中的相應URL,該註冊ID可以將註冊ID插入並存儲,例如與用戶或類似用戶一起存儲。

+0

你能舉個例子,我可以用嗎?因爲我不知道處理我的http post的鏈接源代碼 –

+0

使用位於http://requestb.in/的bin作爲目的地,然後檢查發送的內容。然後你就會知道你的應用程序可以預期哪些數據,然後進行相應的編碼。 – richsage