在if else语句中执行Corona runtime的addEventListener。

如何在if else条件内运行此函数“Runtime:addEventListener(“notification”,onNotification)”。该函数的作用是注册GCM,但默认情况下每次打开应用程序都会进行注册。我想要的是,调用远程数据库,保存该设备的RegID,如果存在,则不要再次向GCM注册。我该怎么做?

local function networkListener(event)
    if (event.isError) then
        print("网络错误!")
    else
        local json = require "json"
        local t = json.decode(event.response)
        local status = t.status
        local isReg = t.isRegistered
        print(event.response)
        if (isReg == "1") then
            native.showAlert("成功", isReg, {"确定"})
        else
            native.showAlert("失败", isReg, {"确定"})
            Runtime:addEventListener("notification", onNotification)
        end

    end
end

##以下是onNotification运行时函数

--当接收到通知事件时调用。
local function onNotification(event)
    print(“onNotification运行”)

    if event.type ==“remoteRegistration”then
        --此设备刚刚为Google Cloud Messaging(GCM)推送通知注册。
        -通过Google分配给此应用程序的存储注册ID。
        googleRegistrationId = event.token

        --显示消息,指示注册成功。
        local message =“此应用程序已成功注册Google推送通知。”
        --native.showAlert("Information", message, { "OK" })
        printTable(message);

        local function submitReg(event)
            if (event.isError) then
                print(“网络错误!”)
            else
                local json = require "json"
                local t = json.decode(event.response)
                print(t)
            end
        end

        local headers = {}

        headers [“Content-Type”] =“application / x-www-form-urlencoded”
        headers [“Accept-Language”] =“en-US”

        local body =“key = 5b41b02152251a3c19a5c3ac88c074cf11aacb19&uid =”.. tostring(googleRegistrationId)

        local params = {}
        params.headers = headers
        params.body = body

        print(“running submit”,body)

        network.request(“http://www.domain.com/api.php?package = com.sample.app&platform = android&action = register”,“POST”,submitReg,params)

        打印注册事件到日志中。
        print(“###---注册事件---”)
        printTable(event)

    else
        -刚刚收到推送通知。将其打印到日志中。
        print(“###---Notification Event ---”)
        printTable(event.response)
    end
end

以上是我的当前代码。运行时函数不会在if else条件中执行。我怎样才能使它执行?

点赞
用户3041972
用户3041972

这是因为在你运行检查时,网络请求仍在进行中。

试试这个:

local function networkListener( event )
 if event.phase == "ended" then

    if ( event.isError ) then
            print( "网络错误!")
    else
            local json = require "json"
            local t = json.decode(event.response)
            local status = t.status
            local isReg = t.isRegistered
            print(event.response)
            if (isReg == "1") then
                native.showAlert("成功",isReg,{"确定"})
            else
                native.showAlert("失败",isReg,{"确定"})
                Runtime:addEventListener("notification", onNotification)
            end

    end
end

end
2015-05-28 08:20:00