0

我使用示例代码来学习,但没有将 RegId 发送到服务器。调用是正确的,因为服务器接受它,没有错误,并在数据库中添加一行但 regid 字符串为空。我研究了几个小时的代码,但不知道出了什么问题。

主要活动

    GCMRegistrar.checkDevice(this);
    GCMRegistrar.checkManifest(this);
    final String regId = GCMRegistrar.getRegistrationId(this);
    if (!regId.equals("")) {
      sendIdToServer(regId);
    } else {
      GCMRegistrar.register(this, Constants.SENDER_ID);
    }

    ...

    private void sendIdToServer(String regId) {
    String status = getString(R.string.gcm_registration, regId);
    mStatus.setText(status);
    (new SendRegistrationIdTask(regId)).execute();
    }

    ...

    private final class SendRegistrationIdTask extends
      AsyncTask<String, Void, HttpResponse> {
    private String mRegId;

    public SendRegistrationIdTask(String regId) {
      mRegId = regId;
    }

    @Override
    protected HttpResponse doInBackground(String... regIds) {
      String url = Constants.SERVER_URL;
      HttpPost httppost = new HttpPost(url);

      try {
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
        nameValuePairs.add(new BasicNameValuePair("regid", mRegId));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpClient httpclient = new DefaultHttpClient();
        return httpclient.execute(httppost);
      } catch (ClientProtocolException e) {
        Log.e(Constants.TAG, e.getMessage(), e);
      } catch (IOException e) {
        Log.e(Constants.TAG, e.getMessage(), e);
      }

      return null;
    }

    @Override
    protected void onPostExecute(HttpResponse response) {
      if (response == null) {
        Log.e(Constants.TAG, "HttpResponse is null");
        return;
      }

      StatusLine httpStatus = response.getStatusLine();
      if (httpStatus.getStatusCode() != 200) {
        Log.e(Constants.TAG, "Status: " + httpStatus.getStatusCode());
        mStatus.setText(httpStatus.getReasonPhrase());
        return;
      }

      String status = getString(R.string.server_registration, mRegId);
      mStatus.setText(status);
    }
  }
4

1 回答 1

1

如果您可以确认(调试) mRegId 在此行中有值:

nameValuePairs.add(new BasicNameValuePair("regid", mRegId));

然后将下一行更改为:

    httpost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));

设置显式编码。

于 2012-11-25T20:28:28.500 回答