无法从CLOUD TO DEVICE消息接收消息

时间:2011-09-13 14:08:58

标签: android service push-notification

以下是我使用云到设备消息传递的实现

1)我在谷歌网站上注册使用c2dm,我也收到了他们的邮件。    所以我想我的邮件ID是正确的

2)在我的启动器活动中,我有以下代码: -

Intent registrationIntent = new Intent("com.google.android.c2dm.intent.REGISTER");
    registrationIntent.putExtra("app", PendingIntent.getBroadcast(this, 0, new  
     Intent(), 0)); // boilerplate
    registrationIntent.putExtra("sender", "mail-id");
    startService(registrationIntent);

3)以下是我的广播接收者代码: -

@Override
public void onReceive(Context context, Intent intent) {
    // TODO Auto-generated method stub
    Log.d("in on recieve", "++++++++++++");
    String a = intent.getAction();
    if(a.equals("com.google.android.c2dm.intent.REGISTRATION")){
        String regId = intent.getStringExtra("registration_id");
        String error = intent.getStringExtra("error");
        String unregistered = intent.getStringExtra("unregistered");
        if(error!=null){

        }else if(regId!=null){
            //Toast.makeText(context, regId, Toast.LENGTH_LONG).show();
            Intent i = new Intent(context, RegService.class);
            i.putExtra("reg", regId);
            context.startService(i);
        }
    }else if(a.equals("com.google.android.c2dm.intent.RECEIVE")){
        String anothr = intent.getAction();
        Toast.makeText(context, anothr, Toast.LENGTH_LONG).show();
        Log.e("C2DM", "Message: Fantastic!!!");
        // Extract the payload from the message
        Bundle extras = intent.getExtras();
        if (extras != null) {
            System.out.println(extras.get("payload"));
            Toast.makeText(context, (CharSequence) extras.get("payload"), Toast.LENGTH_LONG).show();
            // Now do something smart based on the information
        }
    }
}

我可以通过此获取注册ID。然后意图转到我在下一点解释的regService类。

4)以下代码在我的RegService类中。它也在清单文件中提到。

DataManager dataManager = DataManager.getInstance();
String regId;
String appId;
String s;

public RegService(){
    super("Let it be");
    //Toast.makeText(getApplicationContext(), "I got the power", Toast.LENGTH_LONG).show();
    // TODO Auto-generated constructor stub
}

@Override
protected void onHandleIntent(Intent intent) {
    // TODO Auto-generated method tub
    Log.d("In IntentService","++++++++++++++");
     regId = intent.getStringExtra("reg");
     appId = dataManager.getAppUserId();

    TelephonyManager telephonyManager = (TelephonyManager)this.getSystemService(TELEPHONY_SERVICE);
    String devId = telephonyManager.getDeviceId();
    Log.d("Reg Service", "regID -> "+regId+" devId -> "+devId);

    authentification();
}

public void authentification(){
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(
            "https://www.google.com/accounts/ClientLogin");
    try {

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
        nameValuePairs.add(new BasicNameValuePair("Email", "MAIL-ID"));
        nameValuePairs.add(new BasicNameValuePair("Passwd", "piku13nayahai"));
        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=")) {

                 s = line.substring(5);
                Log.d("Authentication Token",s);
                //Toast.makeText(this, s, Toast.LENGTH_LONG).show();
            }

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

    sendMessage();
}

public void sendMessage(){
    try{
    StringBuilder postDataBuilder = new StringBuilder();
    postDataBuilder.append("registration_id").append("=")
    .append(regId);
    postDataBuilder.append("&").append("collapse_key").append("=")
    .append("0");
    postDataBuilder.append("&").append("data.payload").append("=")
    .append(URLEncoder.encode("Some Message", "UTF-8"));
    byte[] postData = postDataBuilder.toString().getBytes("UTF-8");
    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="
            + s);

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

    int responseCode = conn.getResponseCode();

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

    Log.d("Response Code from send API",responseLine+"response code ->"+responseCode);
    // NOTE: You *MUST* use exponential backoff if you receive a 503
    // response code.
    // Since App Engine's task queue mechanism automatically does this
    // for tasks that
    // return non-success error codes, this is not explicitly
    // implemented here.
    // If we weren't using App Engine, we'd need to manually implement
    // this.
    if (responseLine == null || responseLine.equals("")) {
        Log.i("C2DM", "Got " + responseCode
                + " response from Google AC2DM endpoint.");
        throw new IOException(
                "Got empty response from Google AC2DM endpoint.");
    }

    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) {
    // TODO: handle exception
    Log.d("In RegService Catch Block","++++++++++++++++++++++++++++++");
    e.printStackTrace();
}

}

现在问题是我能够从日志Cat本身发送我可以了解的消息。我得到200本身的响应代码,我能够发送消息但无法接收

1 个答案:

答案 0 :(得分:0)

确保您没有使用与收到的电子邮件地址相同的电子邮件地址发送邮件。这显然是围绕着这个问题。