0

I have referred Vogella Tutorial for Android C2DM and implemented client and server as follows.

I've problem with 3 URL's used in application, 1 in client and 2 in server.

In place of 1st URL, there should be server address which I have created. But I don't get what exactly to put there.

Rest of the 2 URL's(sub-URL of google) are not accessible appropriately.

I've highlighted those 3 URL usage by enclosing them with

//==========================================================================

and numbering them.

Note that I'm able to register at the client side but not able to receive any message.

And at server side, I get the authentication but when I try to send the message it gives UnknownHostException.

I know I'm quite unclear in this question but I'm absolute beginner when it comes to Android C2DM development.

Any help appreciated.

Suggest changes if any.

Client code snippet (C2DMRegistrationReceiver.java)

public void sendRegistrationIdToServer(String deviceId,
        String registrationId) {
    Log.d("C2DM", "Sending registration ID to my application server");
    HttpClient client = new DefaultHttpClient();
    HttpPost post;

  // 1.) ========================================================================
 post = new HttpPost("http://vogellac2dm.appspot.com/register");
  //=============================================================================
        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()));
}

Server code snippet

public class ServerSimulator extends Activity {
    private SharedPreferences prefManager;
    private final static String AUTH = "authentication";
    private static final String UPDATE_CLIENT_AUTH = "Update-Client-Auth";
    public static final String PARAM_REGISTRATION_ID = "registration_id";
    public static final String PARAM_DELAY_WHILE_IDLE = "delay_while_idle";
    public static final String PARAM_COLLAPSE_KEY = "collapse_key";
    private static final String UTF8 = "UTF-8";

    // Registration is currently hardcoded
    private final static String YOUR_REGISTRATION_STRING = "APA91bFQut1tqA-nIL1ZaV0emnp4Rb0smwCkrMHcoYRXeYVtIebJgrzOHQj0h76qKRzd3bC_JO37uJ0NgTcFO87HS9V7YC-yOP774pm0toppTHFO7Zc_PAw";

    private SharedPreferences prefs;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        prefManager = PreferenceManager.getDefaultSharedPreferences(this);
    }

    public void getAuthentification(View view) {
        SharedPreferences prefs = PreferenceManager
                .getDefaultSharedPreferences(this);

        HttpClient client = new DefaultHttpClient();
  // 2.) ==========================================================================
        HttpPost post = new HttpPost(
                "https://www.google.com/accounts/ClientLogin");
  //==============================================================================

        try {

            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
            nameValuePairs.add(new BasicNameValuePair("Email", prefs.getString(
                    "user", "myUserName@gmail.com")));
            nameValuePairs.add(new BasicNameValuePair("Passwd", prefs
                    .getString("password", "myPassword")));
            nameValuePairs.add(new BasicNameValuePair("accountType", "GOOGLE"));
            nameValuePairs.add(new BasicNameValuePair("source",
                    "Google-cURL-Example"));
            nameValuePairs.add(new BasicNameValuePair("service", "ac2dm"));

            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);
                if (line.startsWith("Auth=")) {
                    Editor edit = prefManager.edit();
                    edit.putString(AUTH, line.substring(5));
                    edit.commit();
                    String s = prefManager.getString(AUTH, "n/a");
                    Toast.makeText(this, s, Toast.LENGTH_LONG).show();
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void sendMessage(View view) {
        try {
            Log.e("sendMessage", "Started");
            String auth_key = prefManager.getString(AUTH, "n/a");
            // Send a sync message to this Android device.
            StringBuilder postDataBuilder = new StringBuilder();
            postDataBuilder.append(PARAM_REGISTRATION_ID).append("=")
                    .append(YOUR_REGISTRATION_STRING);

            postDataBuilder.append("&").append(PARAM_COLLAPSE_KEY).append("=")
                    .append("0");

            postDataBuilder.append("&").append("data.payload").append("=")
                    .append(URLEncoder.encode("Lars war hier", UTF8));

            byte[] postData = postDataBuilder.toString().getBytes(UTF8);

            // Hit the dm URL.
  // 3.) ==========================================================================
            URL url = new URL("https://android.clients.google.com/c2dm/send");
  //===============================================================================

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded;charset=UTF-8");
            conn.setRequestProperty("Content-Length",
                    Integer.toString(postData.length));
            conn.setRequestProperty("Authorization", "GoogleLogin auth="
                    + auth_key);

            OutputStream out = conn.getOutputStream();
            out.write(postData);
            out.close();

            int responseCode = conn.getResponseCode();

            Log.e("Response Code=", String.valueOf(responseCode));
            // Validate the response code
            // Check for updated token header
            String updatedAuthToken = conn.getHeaderField(UPDATE_CLIENT_AUTH);
            if (updatedAuthToken != null && !auth_key.equals(updatedAuthToken)) {
                Log.i("C2DM",
                        "Got updated auth token from datamessaging servers: "
                                + updatedAuthToken);
                Editor edit = prefManager.edit();
                edit.putString(AUTH, updatedAuthToken);
            }

            String responseLine = new BufferedReader(new InputStreamReader(
                    conn.getInputStream())).readLine();

            String[] responseParts = responseLine.split("=", 2);
            if (responseParts.length != 2) {
                Log.e("C2DM", "Invalid message from google: " + responseCode
                        + " " + responseLine);
                throw new IOException("Invalid response from Google "
                        + responseCode + " " + responseLine);
            }

            if (responseParts[0].equals("id")) {
                Log.i("Tag", "Successfully sent data message to device: "
                        + responseLine);
            }

            if (responseParts[0].equals("Error")) {
                String err = responseParts[1];
                Log.w("C2DM",
                        "Got error response from Google datamessaging endpoint: "
                                + err);
                // No retry.
                throw new IOException(err);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
GAMA
  • 5,958
  • 14
  • 79
  • 126

1 Answers1

1

For URL 1, you need to implement some kind of datastore on a server somewhere that can take requests from registered handsets and store their registration ids so you can later send c2dm notifications to them. In my case, I used an apache2 server that accepts xml over https.

For URL 2, it kind of sounds like you already got that working, since you say "And at server side, I get the authentication". What exactly are you looking for here?

For URL 3, you should be using https://android.apis.google.com/c2dm/send according to the google c2dm docs. Although the address you used resolves for me. Note that the ssl cert google uses for the url above is wrong and won't properly validate, so you may run into that if you're trying to securely send notifications. Did your emulator/handset have internet access when you tested? I'm not sure why else you'd get an UnknownHost exception for that url.

hankystyles
  • 511
  • 2
  • 8
  • for URL 1, I've created server. I just don't know how to link client and server. – GAMA Feb 06 '12 at 05:37
  • URL 3 - Tried the above URL as specified by you, it gives `request time failed: java.net.SocketException: Address family not supported by protocol`... What might be the problem? – GAMA Feb 06 '12 at 05:41
  • @GAMA URL 1: i'm not sure what you mean by 'link them'. one would usually just send the registration id along with some kind of unique identifier for the handset to the server. – hankystyles Feb 06 '12 at 15:31
  • @GAMA URL 3: not sure i can be of much help there. i don't have any experience with HttpUrlConnection. i used HttpClient like you do in your google login request and it works fine for me. – hankystyles Feb 06 '12 at 15:32
  • I'll try 2 sort out URL 3. About URL 1, linking them means, client will register with server and server will send messages to the registered clients. – GAMA Feb 07 '12 at 05:01