GCM Sample Project给出了将 GCM token 发送到服务器的简单示例:
public class RegistrationIntentService extends IntentService {
...
@Override
protected void onHandleIntent(Intent intent) {
try {
...
String token = instanceID.getToken(getString(R.string.gcm_defaultSenderId),
GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
Log.i(TAG, "GCM Registration Token: " + token);
// TODO: Implement this method to send any registration to your app's servers.
sendRegistrationToServer(token);
...
} catch (Exception e) {
...
}
}
/**
* Persist registration to third-party servers.
*
* Modify this method to associate the user's GCM registration token with any server-side account
* maintained by your application.
*
* @param token The new token.
*/
private void sendRegistrationToServer(String token) {
// Add custom implementation, as needed.
}
}
但是这是在 IntentService
中完成的,一旦 onHandleIntent
返回就完成,对吗?因此,如果启动 http 调用以使用流行的 android-async-http 发送 token 库,我什至没有看到我的 onStart
点击:
private void sendRegistrationToServer(String token) {
post("/devices", params, new AsyncHttpResponseHandler() {
// TODO: MAKE SURE ONSTART ACTUALLY CALLED TO MAKE SURE REQUEST AT LEAST GOES UPSTREAM EVEN IF I DON'T RECEIVE A CALLBACK SINCE IN INTENTSERVICE
// IF NOT THEN MIGHT HAVE TO CHANGE THE INTENTSERVICE TO A SERVICE FOR DEVICE REGISTRATION
@Override
public void onStart() {
// not actually using callback because request sent from intentservice
Log.d("tagzzz", "sending upstream");
}
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
// not actually using callback because request sent from intentservice
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
// not actually using callback because request sent from intentservice
}
});
}
在 onHandleIntent
返回并完成 IntentService
之前,我的 http 请求是否会被发送到上游?如果没有,为什么 Google 会给出这个作为将 token 发送到服务器的示例?
最佳答案
Will my http request even be sent upstream before onHandleIntent returns and finishes the IntentService?
鉴于您正在使用名为“android-async-http”的库,我假设它的默认行为是异步执行 HTTP。不确定 post()
调用是否会在 onHandleIntent()
返回之前完成其工作,但似乎不太可能。
why does Google give this as their example for sending your token to your server?
谷歌没有。 Google 有一个 stub sendRegistrationToServer()
,如您在第一个代码 list 中所见。我不知道有任何使用“android-async-http”库的 Google 示例。
您决定使用异步机制发送该 HTTP 请求。对于 IntentService 内部来说,这是一个不合适的选择。现在,也许该库有一个同步选项,在这种情况下您可以切换到该选项。否则,请使用来自 IntentService
的其他同步 HTTP 请求(HttpURLConnection
、OkHttp3 等)。
请注意,Volley 在这里并不是一个很好的选择,因为 Volley 也强烈倾向于异步工作。
关于Android GCM 向服务器发送 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36501842/