草庐IT

android - phonegap android 注册 gcm

coder 2023-12-23 原文

我是 phonegap 的新手,正在尝试为 android 开发一个应用程序以使其在 GCM 中注册。我已经在谷歌 API 中设置了项目。我正在按照 PushPlugin 中的步骤进行操作。尽管我无法获取设备的注册 ID,但我已经设法让代码运行。我正在模拟器上进行测试。

我的 index.html 代码:

<!DOCTYPE HTML>
<html>
    <head>
        <title>com.PhoneGap.c2dm</title>
    </head>
    <body>

        <!--<script type="text/javascript" charset="utf-8" src="cordova-2.2.0.js"></script>-->
        <script type="text/javascript" charset="utf-8" src="cordova.js"></script>
        <script type="text/javascript" charset="utf-8" src="jquery_1.5.2.min.js"></script>
        <script type="text/javascript" src="PushNotification.js"></script>

        <script type="text/javascript">
            var pushNotification;

            function onDeviceReady() {
                $("#app-status-ul").append('<li>deviceready event received</li>');

                document.addEventListener("backbutton", function(e)
                {
                    $("#app-status-ul").append('<li>backbutton event received</li>');

                    if( $("#home").length > 0)
                    {
                        // call this to get a new token each time. don't call it to reuse existing token.
                        //pushNotification.unregister(successHandler, errorHandler);
                        e.preventDefault();
                        navigator.app.exitApp();
                    }
                    else
                    {
                        navigator.app.backHistory();
                    }
                }, false);

                try 
                { 
                    console.log("Inside Try-Catch");
                    pushNotification = window.plugins.pushNotification;
                    if (device.platform == 'android' || device.platform == 'Android') {
                        $("#app-status-ul").append('<li>registering android</li>');
                        pushNotification.register(successHandler, errorHandler, {"senderID":"registration_id","ecb":"onNotificationGCM"});      // required!
                    } else {
                        $("#app-status-ul").append('<li>registering iOS</li>');
                        pushNotification.register(tokenHandler, errorHandler, {"badge":"true","sound":"true","alert":"true","ecb":"onNotificationAPN"});    // required!
                    }
                }
                catch(err) 
                { 
                    txt="There was an error on this page.\n\n"; 
                    txt+="Error description: " + err.message + "\n\n"; 
                    alert(txt); 
                } 
            }

            // handle APNS notifications for iOS
            function onNotificationAPN(e) {
                if (e.alert) {
                     $("#app-status-ul").append('<li>push-notification: ' + e.alert + '</li>');
                     navigator.notification.alert(e.alert);
                }

                if (e.sound) {
                    var snd = new Media(e.sound);
                    snd.play();
                }

                if (e.badge) {
                    pushNotification.setApplicationIconBadgeNumber(successHandler, e.badge);
                }
            }

            // handle GCM notifications for Android
            function onNotificationGCM(e) {
                console.log("Inside onOnNotificationGCM");
                $("#app-status-ul").append('<li>EVENT -> RECEIVED:' + e.event + '</li>');

                switch( e.event )
                {
                    case 'registered':
                    if ( e.regid.length > 0 )
                    {
                        $("#app-status-ul").append('<li>REGISTERED -> REGID:' + e.regid + "</li>");
                        // Your GCM push server needs to know the regID before it can push to this device
                        // here is where you might want to send it the regID for later use.
                        console.log("regID = " + e.regID);
                    }
                    break;

                    case 'message':
                        // if this flag is set, this notification happened while we were in the foreground.
                        // you might want to play a sound to get the user's attention, throw up a dialog, etc.
                        if (e.foreground)
                        {
                            $("#app-status-ul").append('<li>--INLINE NOTIFICATION--' + '</li>');

                            // if the notification contains a soundname, play it.
                            var my_media = new Media("/android_asset/www/"+e.soundname);
                            my_media.play();
                        }
                        else
                        {   // otherwise we were launched because the user touched a notification in the notification tray.
                            if (e.coldstart)
                                $("#app-status-ul").append('<li>--COLDSTART NOTIFICATION--' + '</li>');
                            else
                            $("#app-status-ul").append('<li>--BACKGROUND NOTIFICATION--' + '</li>');
                        }

                        $("#app-status-ul").append('<li>MESSAGE -> MSG: ' + e.payload.message + '</li>');
                        $("#app-status-ul").append('<li>MESSAGE -> MSGCNT: ' + e.payload.msgcnt + '</li>');
                    break;

                    case 'error':
                        $("#app-status-ul").append('<li>ERROR -> MSG:' + e.msg + '</li>');
                    break;

                    default:
                        $("#app-status-ul").append('<li>EVENT -> Unknown, an event was received and we do not know what it is</li>');
                    break;
                }
            }

            function tokenHandler (result) {
                $("#app-status-ul").append('<li>token: '+ result +'</li>');
                // Your iOS push server needs to know the token before it can push to this device
                // here is where you might want to send it the token for later use.
            }

            function successHandler (result) {
                $("#app-status-ul").append('<li>success:'+ result +'</li>');
            }

            function errorHandler (error) {
                $("#app-status-ul").append('<li>error:'+ error +'</li>');
            }

            document.addEventListener('deviceready', onDeviceReady, true);

         </script>
        <div id="home">
            <div id="app-status-div">
                <ul id="app-status-ul">
                    <li>Cordova PushNotification Plugin Demo</li>
                </ul>
            </div>
        </div>
    </body>
</html>

有什么我遗漏或做错的吗?

编辑:我添加了一些日志并确定在调用 successHandler() 之后未调用 onNotificationGCM() 方法

最佳答案

为了阐明 pushNotification.register 的配置对象中提供的“ecb”处理程序将通过“已注册”事件被调用。注册 ID 将在“ecb”处理程序提供的对象参数内提供。在示例中,这将是“ecb”=“onNotificationGCM”。

function onNotificationGCM(e) {
  if(e.event == "registered") {
    alert(e.regid);
  }
}

关于android - phonegap android 注册 gcm,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19806848/

有关android - phonegap android 注册 gcm的更多相关文章

  1. 阿里云国际版免费试用:如何注册以及注意事项 - 2

    作为新的阿里云用户,您可以50免费试用多种优惠,价值高达1,700美元(或8,500美元)。这将让您了解和体验阿里云平台上提供的一系列产品和服务。如果您以个人身份注册免费试用,您将获得价值1,700美元的优惠。但是,如果您是注册公司,您可以选择企业免费试用,提交基本信息通过企业实名注册验证,即可开始价值$8,500的免费试用!本教程介绍了如何设置您的帐户并使用您的免费试用版。​关于免费试用在我们开始此试用之前,您还必须遵守以下条款和条件才能访问您的免费试用:只有在一年内创建的账户才有资格获得阿里云免费试用。通过此免费试用优惠,用户可以免费试用免费试用活动页面上列出的每种产品一次。如果您有多个帐

  2. 安卓apk修改(Android反编译apk) - 2

    最近因为项目需要,需要将Android手机系统自带的某个系统软件反编译并更改里面某个资源,并重新打包,签名生成新的自定义的apk,下面我来介绍一下我的实现过程。APK修改,分为以下几步:反编译解包,修改,重打包,修改签名等步骤。安卓apk修改准备工作1.系统配置好JavaJDK环境变量2.需要root权限的手机(针对系统自带apk,其他软件免root)3.Auto-Sign签名工具4.apktool工具安卓apk修改开始反编译本文拿Android系统里面的Settings.apk做demo,具体如何将apk获取出来在此就不过多介绍了,直接进入主题:按键win+R输入cmd,打开命令窗口,并将路

  3. ruby-on-rails - 设计注册确认 - 2

    我在我的项目中有一个用户和一个管理员角色。我使用Devise创建了身份验证。在我的管理员角色中,我没有任何确认。在我的用户模型中,我有以下内容:devise:database_authenticatable,:confirmable,:recoverable,:rememberable,:trackable,:validatable,:timeoutable,:registerable#Setupaccessible(orprotected)attributesforyourmodelattr_accessible:email,:username,:prename,:surname,:

  4. ruby-on-rails - 特征未注册 : attribute name - 2

    完成这个有困难。我正在使用seed.rb+factory_girl来使用rakedb:seed填充数据库。(我知道固定装置存在,但我想以这种方式完成,这只是一个示例,数据库将填充复杂的关联对象。)我的种子.rb:require'factory_girl_rails'["QM","CDC","SI","QS"].eachdo|n|FactoryGirl.create(:grau,nome:n)end还有我的/factories/graus.rbFactoryGirl.definedofactory:graudonomeendend但是当我运行时:rakedb:seed我得到:rakeab

  5. ruby-on-rails - 带有自定义处理器的 CarrierWave 未注册 - 2

    我正在使用carrierwave上传视频然后有一个名为thumb的版本,带有自定义处理器,可以获取视频并使用streamio-ffmpeg创建屏幕截图。视频和文件都已正确上传,但在调用uploader.url(:thumb)时我得到:ArgumentError:Versionthumbdoesn'texist!VideoUploader.rbrequire'carrierwave/processing/mime_types'require'streamio-ffmpeg'classVideoUploader5)File.renamethumb_path,current_pathendd

  6. ruby-on-rails - 如何访问设计 token 授权注册 Controller ? - 2

    我正在使用Deviseauthtokengem用于验证我的Rails应用程序的某些部分。但是,当我尝试使用注册路径创建新用户时,出现以下错误{"errors":["Authorizedusersonly."]}。这是我用于测试的rspec代码,it'createsauserusingemail/passwordcombo'dopostapi_user_registration_path,{email:'xxx',password:'yyy',password_confirmation:'yyy'}putslast_response.bodyexpect(last_response.bo

  7. ruby - 如何将 Thor::Group 注册为带参数的子命令 - 2

    这道题开始于here.但随着我对雷神的了解越来越多,情况发生了很大变化。我正在尝试创建一个带参数的Thor::Group子命令。奇怪的是,如果没有参数,它就可以工作。我可以使用Thor::Group作为子命令吗?这在我输入时有效:foocounterfoo/bin/foomoduleFooclassCLI但是当我输入时这不起作用:foocounter5moduleFooclassCLI','Countupfromtheinput.')endclassCounter:numeric,:desc=>"Thenumbertostartcounting"desc"Prints2numbersb

  8. Ruby - 不支持的密码算法 (AES-256-GCM) - 2

    我收到错误:unsupportedcipheralgorithm(AES-256-GCM)(RuntimeError)但我似乎具备所有要求:ruby版本:$ruby--versionruby2.1.2p95OpenSSL会列出gcm:$opensslenc-help2>&1|grepgcm-aes-128-ecb-aes-128-gcm-aes-128-ofb-aes-192-ecb-aes-192-gcm-aes-192-ofb-aes-256-ecb-aes-256-gcm-aes-256-ofbRuby解释器:$irb2.1.2:001>require'openssl';puts

  9. ruby-on-rails - 在设计注册中保留查询字符串 - 2

    我正在使用railswithdevise进行注册。我还添加了一个邀请码,所以不是每个人都可以注册。邀请码通过“/users/sign_up?invite_code=wajdpapojapsd”之类的查询字符串传输,并使用“f.hidden_​​field:invite_code,:value=>params[”添加到注册表单的隐藏字段中:invite_code]".这很好用。唯一的问题是,如果注册没有得到验证和拒绝,设计重定向到“/users”并丢失带有invite_code的查询字符串。由于电子邮件在尝试失败后保留在注册表单中,我相信这也适用于邀请代码。作为最坏情况的解决方案,在注册

  10. ruby-on-rails - Rails 4 - 设计:在注册时获取 ActionController::UnknownFormat - 2

    我有一个Rails4.2.3应用程序,我在其中使用Devise进行用户身份验证。我在Bootstrap模式中展示我的注册表单。我已经实现了类似于:https://github.com/plataformatec/devise/wiki/How-To:-Display-a-custom-sign_in-form-anywhere-in-your-app.注册时我不断收到此错误:Completed406NotAcceptablein512033ms(ActiveRecord:5.8ms)ActionController::UnknownFormat(ActionController::Un

随机推荐