2012-05-03 4 views
0

私はVogella C2DM tutorialのチュートリアルに従いましたが、C2DMの理解を深めている人のように、コードを取得するのは素晴らしいチュートリアルですが、実際の使い方を理解する助けにはなりません。私は自分のAndroidクラスと私のサーバー(PHPに移植)をセットアップしましたが、今はどのように進めるのか分かりません。わかりにくいAndroid C2DM

function googleAuthenticate($username, $password, $source="Company-AppName-Version", $service="ac2dm") { 
    session_start(); 
    if(isset($_SESSION['google_auth_id']) && $_SESSION['google_auth_id'] != null) 
     return $_SESSION['google_auth_id']; 

    // get an authorization token 
    $ch = curl_init(); 
    if(!ch){ 
     return false; 
    } 

    curl_setopt($ch, CURLOPT_URL, "https://www.google.com/accounts/ClientLogin"); 
    $post_fields = "accountType=" . urlencode('HOSTED_OR_GOOGLE') 
     . "&Email=" . urlencode($username) 
     . "&Passwd=" . urlencode($password) 
     . "&source=" . urlencode($source) 
     . "&service=" . urlencode($service); 
    curl_setopt($ch, CURLOPT_HEADER, true); 
    curl_setopt($ch, CURLOPT_POST, true); 
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
    curl_setopt($ch, CURLOPT_FRESH_CONNECT, true); 
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY); 
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 

    // for debugging the request 
    //curl_setopt($ch, CURLINFO_HEADER_OUT, true); // for debugging the request 

    $response = curl_exec($ch); 

    //var_dump(curl_getinfo($ch)); //for debugging the request 
    //var_dump($response); 

    curl_close($ch); 

    if (strpos($response, '200 OK') === false) { 
     return false; 
    } 

    // find the auth code 
    preg_match("/(Auth=)([\w|-]+)/", $response, $matches); 

    if (!$matches[2]) { 
     return false; 
    } 

    $_SESSION['google_auth_id'] = $matches[2]; 
} 

function sendMessageToPhone($authCode, $deviceRegistrationId, $msgType, $messageText) { 

    $headers = array('Authorization: GoogleLogin auth=' . $authCode); 
    $data = array(
     'registration_id' => $deviceRegistrationId, 
     'collapse_key' => $msgType, 
     'data.message' => $messageText //TODO Add more params with just simple data instead   
    ); 

    $ch = curl_init(); 

    curl_setopt($ch, CURLOPT_URL, "https://android.apis.google.com/c2dm/send"); 
    if ($headers) 
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); 
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
    curl_setopt($ch, CURLOPT_POST, true); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data); 


    $response = curl_exec($ch); 

    curl_close($ch); 

    return $response; 
} 

C2DMRegistrationReceiver.java

@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); 
     // TODO Send this to my application server 
    } 
} 

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("myserverpage"); 
    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(); 
    } 
} 

C2DMMessageReceiver.java

@Override 
public void onReceive(Context context, Intent intent) { 
    String action = intent.getAction(); 
    Log.w("C2DM", "Message Receiver called"); 
    if ("com.google.android.c2dm.intent.RECEIVE".equals(action)) { 
     Log.w("C2DM", "Received message"); 
     final String payload = intent.getStringExtra("payload"); 
     Log.d("C2DM", "dmControl: payload = " + payload); 
     // Send this to my application server 
    } 
} 

そして、私のMainActivityのIに

c2dm.php(サーバー側):私のコードは次のようになります。持っているのは

public void register() { 
    Intent intent = new Intent("com.google.android.c2dm.intent.REGISTER"); 
    intent.putExtra("app",PendingIntent.getBroadcast(this, 0, new Intent(), 0)); 
    intent.putExtra("sender", "[email protected]"); 
    startService(intent); 
} 

アプリケーションの起動中にregister()を呼び出すと、LogCatに「Message Receiver called」と表示され、「Received Receiver」は呼び出されません。私はもちろん、[email protected]を私自身に変更しましたが、コードの使用方法はわかりません。私を助けることができる人?

ありがとうございます!

+0

Android C2DMの場合、マニフェストコードはソースと同じくらい重要です。多くの宣言が残っていて、正しく動作しなくなる可能性があります。 – Warpzit

答えて

2

にVogellaのチュートリアルは非常にシンプルで簡単です。あなたがそれを一歩一歩踏んできたのであれば、それほど苦労しないでしょう。

あなたのロガーにはというメッセージレシーバーがあります。これは、C2DMMessageReceiverでログするメッセージであるため、と呼ばれています。登録するレシーバーがもう1つある場合は、マニフェストでそれを宣言し、ここにコードを投稿してください。

同じ受信機クラスを使用することをおすすめします。私はあなたがより多くのアクションを置くことができ、コメントを追加している

if (action != null){ 
     // This is for registration 
     if (action.equals("com.google.android.c2dm.intent.REGISTRATION")){ 
      Log.d(LOG_TAG, "Received registration ID"); 

      final String registrationId = intent.getStringExtra("registration_id"); 
      String error = intent.getStringExtra("error"); 

      Log.d(LOG_TAG, "dmControl: registrationId = " + registrationId + ", error = " + error); 

      // Create a notification with the received registration id 

      // Also save it in the preference to be able to show it later 

      // Get the device id in order to send it to the server 
      String deviceId = Secure.getString(context.getContentResolver(), Secure.ANDROID_ID); 
      // .. send it to the server 
     } 
     // This is for receiving messages 
     else if (action.equals("com.google.android.c2dm.intent.RECEIVE")){ 
      String payload = intent.getStringExtra("payload"); 
      Log.d(LOG_TAG, "Message received: " + payload); 
      // .. create a notification with the new message 
     } 

(サードパーティのサーバーに登録IDを送信し、作成した通知のように、など):たとえば、ここでは簡単なonReceive方法です。上記のことを行う方法の例は、Lars Vogelのチュートリアルにもあります。

+0

ありがとうございました!私は数分後にそれをチェックし、どのように行ったかについてあなたに戻ってきます! – simtaxman

+0

私は今、それを保持しているようだ、私はちょうど私のコードなどで実装するつもりだが、助けてくれてありがとう! – simtaxman

+0

ようこそ。 –

0

私の場合は、両方のための単一の受信機使用しています:

if (action.equals("com.google.android.c2dm.intent.REGISTRATION")) { 
String registrationId = intent.getStringExtra("registration_id"); 
//do somting 
} else if (intent.getAction().equals("com.google.android.c2dm.intent.RECEIVE")) { 
Bundle extras = intent.getExtras(); 
String message = extras.getString("message"); 
}// end if 

} 

をマニフェスト

<receiver 
    android:name=".receiverName" 
android:permission="com.google.android.c2dm.permission.SEND" > 
    <intent-filter> 
<action android:name="com.google.android.c2dm.intent.RECEIVE" /> 

<category android:name="packageName" /> 
</intent-filter> 
<intent-filter> 
<action android:name="com.google.android.c2dm.intent.REGISTRATION" /> 

<category android:name="packageName" /> 
</intent-filter> 
+0

Okey、忘れましたが、マニフェストにも正しいアクセス許可があります。しかし、どのように私は登録から行く - >メッセージを送信する - >私のアプリケーションでそれを受け取りますか?それは私の問題、それを使用する方法の全体的な理解です。 – simtaxman

0

私が理解したことを説明します。

  1. まず、Androidアプリのパッケージ名とアンドロイドC2DMサイトに登録あなたが所有してGmailのIDでcom.example.app を言います。

  2. アンドロイドアプリは、デバイス登録IDをリクエストとしてサーバーに送信できる必要があります。サーバーはこれらのIDをdbに格納する必要があります。

  3. サーバーからすべてのデバイスにメッセージをプッシュする準備ができたら、c2dmに登録したgmail idとdbに保存した デバイスIDに新しいauth_tokenを設定するだけです。

Vogellaチュートリアルには、デバイスおよびauth_tokenのregidを取得するためのサンプルコードがあります。私はそれを試して、私のアプリのための変更でそれを使用しました。