创建GCM客户端应用程序,asynctask失败

时间:2013-07-15 10:59:26

标签: google-cloud-messaging

在创建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);

2 个答案:

答案 0 :(得分:0)

正如AlexBcn已经观察到的,并且根据AsyncTask的文档,您将传递给AsyncTask三种类型作为参数。因为您希望将GCM推送通知的有效负载作为String返回,所以您将调用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);
    }

答案 1 :(得分:-1)

这是因为您传入Async任务的参数。 如需进一步帮助: 我最近将功能齐全的GCM java客户端上传到了我的Github帐户: GCM Android Client

它已经实现了服务器和客户端。