0

i already coding an ac2dm application, i follow this tutorial,

but... i found something strange with the code... here's the code..

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

Look at this pary HttpPost post = new HttpPost("http://vogellac2dm.appspot.com/register");

why i must send the data here?? anyone knows? because when i try to visit it i found that the link is dead...

thanks before

================================== hey... i already fix it... but now i get new trouble... i get trouble with the content... when i try to send it from my php, i get a warning like this

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

This is the php code...

<?php
        $host           =       'localhost';
        $user           =       'k8xxx_kiosban';
        $pass           =       'k8xxx';
        $database       =       'k8k8xxx_kiosban';
        $username ="xxxx@gmail.com";
        $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;?>

And then, when i try to send, i get a notification, but sometimes the content not same with what i sent...

example, first i send a message "Tes percobaan", on my device i get "Tes percobaan", but if i sent it again with a message "percobaaan" i get a notification on my device, but the content is "Tes percobaan" <-- the content before

so any suggestion here??

1 Answers1

0

The example code you've copied uses the line you're concerned about to send the registration ID back to some server for storage. In most cases this would be to your own application server, so that you can store the registration ID for the device and use it at a later date to send C2DM data to the device.

Since you'll need to know the device's registration ID before sending it data, simply replace this URL with the appropriate URL within your application that can take the registration ID in and store it eg alongside a user or similar.

richsage
  • 26,912
  • 8
  • 58
  • 65
  • can you give me a example that can i use for? because i didnt know that link source code that handle my http post – Wawan Den Frastøtende Jun 14 '12 at 08:32
  • Use a bin at http://requestb.in/ as a destination and then inspecting what you get sent. Then you'll know what data you can expect in your application, and then code accordingly. – richsage Jun 14 '12 at 10:28