gpt4 book ai didi

google-cloud-messaging - 创建 GCM 客户端应用程序,asynctask 失败

转载 作者:行者123 更新时间:2023-12-03 09:00:02 25 4
gpt4 key购买 nike

创建 GCM 客户端应用程序时,asynctask 出现编译错误。OnCreate 我们正在调用 registerBackgrouod,它将检查 gcm 实例是否正在运行,如果没有则创建一个。

但是 asyntask 给出错误:“Asynctask 无法解析为类型”

private void registerBackground() {
new AsyncTask() {
protected String doInBackground(Void... params) {
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(context);
}
regid = gcm.register(SENDER_ID);
msg = "Device registered, registration id=" + regid;
// You should send the registration ID to your server over HTTP,
// so it can use GCM/HTTP or CCS to send messages to your app.
// For this demo: we don't need to send it because the device
// will send upstream messages to a server that echo back the message
// using the 'from' address in the message.

// Save the regid - no need to register again.
setRegistrationId(context, regid);
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
}
return msg;
}


protected void onPostExecute(String msg) {
mDisplay.append(msg + "\n");
}
}.execute(null, null, null);

最佳答案

正如 AlexBcn 已经观察到的,并根据 AsyncTask 的文档,您可以将三种类型作为参数传递给 AsyncTask。因为您想将 GCM 推送通知的有效负载作为字符串返回,所以您将调用 AsyncTask<Void, Void, String>

所以正确的GCM客户端代码片段是:

    private void registerInBackground() {
new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... params) {
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(context);
}
regid = gcm.register(SENDER_ID);
msg = "Device registered, registration ID=" + regid;

// You should send the registration ID to your server over HTTP, so it
// can use GCM/HTTP or CCS to send messages to your app.
// For this demo: we don't need to send it because the device will send
// upstream messages to a server that echo back the message using the
// 'from' address in the message.

// Persist the regID - no need to register again.
storeRegistrationId(context, regid);
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
// If there is an error, don't just keep trying to register.
// Require the user to click a button again, or perform
// exponential back-off.
}
return msg;
}.execute(null, null, null);
}

关于google-cloud-messaging - 创建 GCM 客户端应用程序,asynctask 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17652657/

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