gpt4 book ai didi

android - 如何在实现 GCM 时从 Android 应用程序调用服务器应用程序 Servlet 以注册设备

转载 作者:搜寻专家 更新时间:2023-11-01 08:02:53 25 4
gpt4 key购买 nike

我正在尝试从开发者 android 站点了解 GCM。我已经按照 http://developer.android.com/google/gcm/client.html 中的说明实现了客户端 android 应用程序和 http 服务器应用程序(不是基于 XMPP 的服务器应用程序)按照 http://developer.android.com/google/gcm/http.html 中的说明进行操作.我使用的代码是从https://code.google.com/p/gcm/下载的正如他们所提到的。 GCM 注册功能在我的手机上完美运行。

现在的问题是,我如何将手机的注册 ID 发送到我的 http 服务器应用程序。我知道我应该在 DemoActivity.java 文件的 sendRegistrationIdToBackend() 中放置一些代码android 应用程序的简单调用我的服务器应用程序上的 RegisterServlet。但我是 java 和 android 的新手,只是不知道该怎么做。非常感谢任何有关我如何编写此代码的建议。

最佳答案

这是使用 HTTP GET 请求将注册 ID 发送到您的服务器的示例代码。我正在使用 org.apache.http.* 库的类。它假设您的服务器上有一个页面接受名为 regId 的参数中的注册 ID(在示例中它是一个 jsp 页面,但它可以是任何您想要的 PHP在您的服务器中)。您必须添加错误处理代码和解析服务器响应才能完成此示例。

  String responseString= null;

try {
URI url = new URI ("http://your-server-domain/your-server-page.jsp?regId="+THE_REGISTRATION_ID);
HttpGet httpGet = new HttpGet (url);
// defaultHttpClient
HttpParams
httpParameters = new BasicHttpParams();

// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used.
int
timeoutConnection= 3000;
HttpConnectionParams.setConnectionTimeout (
httpParameters,
timeoutConnection
);

// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout (
httpParameters,
timeoutSocket
);

DefaultHttpClient
httpClient = new DefaultHttpClient (httpParameters);

HttpResponse
httpResponse = httpClient.execute (httpGet);
HttpEntity
httpEntity = httpResponse.getEntity ();

if (httpResponse.getStatusLine().getStatusCode() != 200)
{
Log.e (
_context.getString(R.string.app_name),
"Server Call Failed : Got Status Code " + httpResponse.getStatusLine().getStatusCode() + " and ContentType " + httpEntity.getContentType().getValue()
);
// add code to handle error
}

responseString = EntityUtils.toString (httpEntity);
} catch (UnsupportedEncodingException e) {
Log.e(_context.getString(R.string.app_name),e.toString(),e);
// add code to handle error
} catch (ClientProtocolException e) {
Log.e(_context.getString(R.string.app_name),e.toString(),e);
// add code to handle error
} catch (IOException e) {
Log.e(_context.getString(R.string.app_name),e.toString(),e);
// add code to handle error
} catch (URISyntaxException e) {
Log.e(_context.getString(R.string.app_name),e.toString(),e);
// add code to handle error
}

关于android - 如何在实现 GCM 时从 Android 应用程序调用服务器应用程序 Servlet 以注册设备,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18551266/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com