守望者--AIR技术交流

标题: air 3.4 移动开发使用后台推送通知 [打印本页]

作者: 破晓    时间: 2015-1-6 15:18
标题: air 3.4 移动开发使用后台推送通知
  • 推送通知概述
    • 注册工作流程
    • 通知工作流程
    • 推送通知 API
  • 在应用程序中管理推送通知
    • 在应用程序 XML 文件中启用推送通知
    • 创建启用 iOS Push Services 的供给配置文件和证书
    • 对推送通知使用声音。
    • 使用已本地化的警告通知
  • 配置远程通知提供方
    • 远程通知提供方选项
    • 远程通知提供方证书
  • 在应用程序中处理推送通知
    • 推送通知的配置和接受
    • 处理推送通知和有效载荷数据





推送通知使远程通知提供方将通知发送至在移动设备中运行的应用程序。针对使用 Apple 推送通知服务 (APNs) 的 iOS 设备,AIR 3.4 支持推送通知。
注: 要针对 AIR for Android 应用程序启用推送通知,请使用本机扩展,例如由 Adobe evangelist Piotr Walczyszyn 开发的 as3c2dm
本章节其余部分描述了如何在 AIR for iOS 应用程序中启用推送通知。
注: 该讨论假定您拥有 Apple 开发人员 ID,熟悉 iOS 开发工作流程,并且已在一台 iOS 设备上至少部署了一个应用程序。


推送通知概述
Apple 推送通知服务 (APNs) 使远程通知提供方将通知发送至在 iOS 设备中运行的应用程序。APNs 支持以下通知类型:
关于 APNs 的完整信息,请参阅 developer.apple.com
在应用程序中使用推送通知涉及到多个方面:


注册工作流程
在服务器端服务中注册推送通知的工作流程如下:
  • 客户端应用程序要求 iOS 启用推送通知。
  • iOS 向 APNs 转发该请求。
  • APNs 服务器将一个 tokenId 返回至 iOS。
  • iOS 将 tokenId 返回至客户端应用程序。
  • 客户端应用程序(使用特定于应用程序的机制)向远程通知提供方提供 tokenId,远程通知提供方储存 tokenId 用于推送通知。



通知工作流程
通知工作流程如下:
  • 远程通知提供方生成一个通知,并将通知有效载荷与 tokenId 一起传递至 APNs。
  • APNs 将通知转发至设备中的 iOS。
  • iOS 将通知有效载荷推送至应用程序。



推送通知 API
AIR 3.4 采用了一组支持 iOS 推送通知的 API。这些 API 在 flash.notifications 中,并且包含以下类:
AIR 3.4 还包含 flash.events.RemoteNotificationEvent(由RemoteNotifier调度),如下所示:
  • 成功创建应用程序预定和收到来自 APNs 的新 tokenId 时。
  • 接收新的远程通知时。
此外,如果在预定进程期间遇到错误,则 RemoteNotifier 调度 flash.events.StatusEvent。




在应用程序中管理推送通知
要注册推送通知应用程序,必须执行以下步骤:
以下有批注的样本代码预定推送通知并处理推送通知事件:
  1. package
  2. {
  3.     import flash.display.Sprite;
  4.     import flash.display.StageAlign;
  5.     import flash.display.StageScaleMode;
  6.     import flash.events.*;
  7.     import flash.events.Event;
  8.     import flash.events.IOErrorEvent;
  9.     import flash.events.MouseEvent;
  10.     import flash.net.*;
  11.     import flash.text.TextField;
  12.     import flash.text.TextFormat;
  13.     import flash.ui.Multitouch;
  14.     import flash.ui.MultitouchInputMode;
  15.     // Required packages for push notifications
  16.     import flash.notifications.NotificationStyle;
  17.     import flash.notifications.RemoteNotifier;
  18.     import flash.notifications.RemoteNotifierSubscribeOptions;
  19.     import flash.events.RemoteNotificationEvent;
  20.     import flash.events.StatusEvent;
  21.     [SWF(width="1280", height="752", frameRate="60")]

  22.     public class TestPushNotifications extends Sprite
  23.     {
  24.         private var notiStyles:Vector.<String> = new Vector.<String>;;
  25.         private var tt:TextField = new TextField();
  26.         private var tf:TextFormat = new TextFormat();
  27.         // Contains the notification styles that your app wants to receive
  28.         private var preferredStyles:Vector.<String> = new Vector.<String>();
  29.         private var subscribeOptions:RemoteNotifierSubscribeOptions = new RemoteNotifierSubscribeOptions();
  30.         private var remoteNot:RemoteNotifier = new RemoteNotifier();

  31.         private var subsButton:CustomButton = new CustomButton("Subscribe");
  32.         private var unSubsButton:CustomButton = new CustomButton("UnSubscribe");
  33.         private var clearButton:CustomButton = new CustomButton("clearText");

  34.         private var urlreq:URLRequest;
  35.         private var urlLoad:URLLoader = new URLLoader();
  36.         private var urlString:String;

  37.         public function TestPushNotifications()
  38.         {
  39.             super();

  40.             Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT;
  41.             stage.align = StageAlign.TOP_LEFT;
  42.             stage.scaleMode = StageScaleMode.NO_SCALE;

  43.             tf.size = 20;
  44.             tf.bold = true;

  45.             tt.x=0;
  46.             tt.y =150;
  47.             tt.height = stage.stageHeight;
  48.             tt.width = stage.stageWidth;
  49.             tt.border = true;
  50.             tt.defaultTextFormat = tf;

  51.             addChild(tt);

  52.             subsButton.x = 150;
  53.             subsButton.y=10;
  54.             subsButton.addEventListener(MouseEvent.CLICK,subsButtonHandler);
  55.             stage.addChild(subsButton);

  56.             unSubsButton.x = 300;
  57.             unSubsButton.y=10;
  58.             unSubsButton.addEventListener(MouseEvent.CLICK,unSubsButtonHandler);
  59.             stage.addChild(unSubsButton);

  60.             clearButton.x = 450;
  61.             clearButton.y=10;
  62.             clearButton.addEventListener(MouseEvent.CLICK,clearButtonHandler);
  63.             stage.addChild(clearButton);

  64.             //
  65.             tt.text += "n SupportedNotification Styles: " + RemoteNotifier.supportedNotificationStyles.toString() + "n";

  66.             tt.text += "n Before Preferred notificationStyles: " + subscribeOptions.notificationStyles.toString() + "n";

  67.             // Subscribe to all three styles of push notifications:
  68.             // ALERT, BADGE, and SOUND.
  69.             preferredStyles.push(NotificationStyle.ALERT ,NotificationStyle.BADGE,NotificationStyle.SOUND );

  70.             subscribeOptions.notificationStyles= preferredStyles;

  71.             tt.text += "n After Preferred notificationStyles:" + subscribeOptions.notificationStyles.toString() + "n";

  72.             remoteNot.addEventListener(RemoteNotificationEvent.TOKEN,tokenHandler);
  73.             remoteNot.addEventListener(RemoteNotificationEvent.NOTIFICATION,notificationHandler);
  74.             remoteNot.addEventListener(StatusEvent.STATUS,statusHandler);

  75.             this.stage.addEventListener(Event.ACTIVATE,activateHandler);

  76.         }
  77.         // Apple recommends that each time an app activates, it subscribe for
  78.         // push notifications.
  79.         public function activateHandler(e:Event):void{
  80.              // Before subscribing to push notifications, ensure the device supports it.
  81.             // supportedNotificationStyles returns the types of notifications
  82.             // that the OS platform supports
  83.             if(RemoteNotifier.supportedNotificationStyles.toString() != "")
  84.             {
  85.                 remoteNot.subscribe(subscribeOptions);
  86.              }
  87.              else{
  88.                 tt.appendText("n Remote Notifications not supported on this Platform !");
  89.             }
  90.         }
  91.         public function subsButtonHandler(e:MouseEvent):void{
  92.             remoteNot.subscribe(subscribeOptions);
  93.         }
  94.         // Optionally unsubscribe from push notfications at runtime.
  95.         public function unSubsButtonHandler(e:MouseEvent):void{
  96.             remoteNot.unsubscribe();
  97.             tt.text +="n UNSUBSCRIBED";
  98.         }

  99.         public function clearButtonHandler(e:MouseEvent):void{
  100.             tt.text = " ";
  101.         }
  102.         // Receive notification payload data and use it in your app
  103.         public function notificationHandler(e:RemoteNotificationEvent):void{
  104.             tt.appendText("nRemoteNotificationEvent type: " + e.type +
  105.                 "nbubbles: "+ e.bubbles + "ncancelable " +e.cancelable);

  106.             for (var x:String in e.data) {
  107.                 tt.text += "n"+ x + ":  " + e.data[x];
  108.             }
  109.         }
  110.         // If the subscribe() request succeeds, a RemoteNotificationEvent of
  111.         // type TOKEN is received, from which you retrieve e.tokenId,
  112.         // which you use to register with the server provider (urbanairship, in
  113.         // this example.
  114.         public function tokenHandler(e:RemoteNotificationEvent):void
  115.         {
  116.             tt.appendText("nRemoteNotificationEvent type: "+e.type +"nBubbles: "+ e.bubbles + "ncancelable " +e.cancelable +"ntokenID:n"+ e.tokenId +"n");

  117.             urlString = new String("https://go.urbanairship.com/api/device_tokens/" +
  118.                 e.tokenId);
  119.             urlreq = new URLRequest(urlString);

  120.             urlreq.authenticate = true;
  121.             urlreq.method = URLRequestMethod.PUT;

  122.             URLRequestDefaults.setLoginCredentialsForHost
  123.                 ("go.urbanairship.com",
  124.                     "1ssB2iV_RL6_UBLiYMQVfg","t-kZlzXGQ6-yU8T3iHiSyQ");

  125.             urlLoad.load(urlreq);
  126.             urlLoad.addEventListener(IOErrorEvent.IO_ERROR,iohandler);
  127.             urlLoad.addEventListener(Event.COMPLETE,compHandler);
  128.             urlLoad.addEventListener(HTTPStatusEvent.HTTP_STATUS,httpHandler);

  129.         }

  130.         private function iohandler(e:IOErrorEvent):void
  131.         {
  132.             tt.appendText("n In IOError handler" + e.errorID +" " +e.type);

  133.         }
  134.         private function compHandler(e:Event):void{
  135.         tt.appendText("n In Complete handler,"+"status: " +e.type + "n");
  136.         }

  137.         private function httpHandler(e:HTTPStatusEvent):void{
  138.         tt.appendText("n in httpstatus handler,"+ "Status: " + e.status);
  139.         }

  140.         // If the subscription request fails, StatusEvent is dispatched with
  141.         // error level and code.
  142.         public function statusHandler(e:StatusEvent):void{
  143.             tt.appendText("n statusHandler");
  144.             tt.appendText("event Level" + e.level +"nevent code " +
  145.                 e.code + "ne.currentTarget: " + e.currentTarget.toString());
  146.         }
  147.     }
  148. }
复制代码
在应用程序 XML 文件中启用推送通知
要在应用程序中使用推送通知,请在 Entitlements 标签(在 iphone 标签下)中提供以下内容:
  1. <iphone>
  2. ...
  3.    <Entitlements>
  4.       <![CDATA[
  5.          <key>aps-environment</key>
  6.          <string>development</string>
  7.       ]]>
  8.    </Entitlements>
  9. </iphone>
复制代码
当您已准备好将应用程序推送至 App Store 时,用于开发到生产的 <string> 元素:
  1. <string>production</string>
复制代码
如果应用程序支持已本地化的字符串,则请在 supportedLanguages 标签中指定语言,该标签在 intialWindow 标签下,如以下示例所示:
  1. <supportedLanguages>en de cs es fr it ja ko nl pl pt</supportedLanguages>
复制代码
创建启用 iOS Push Services 的供给配置文件和证书
要启用应用程序 – APNs 通信,必须用启用 iOS Push Services 的供给配置文件和证书打包应用程序,如下所示:
  • 登录您的 Apple 开发人员帐户。
  • 导航至 Provisioning Portal。
  • 单击“应用程序 ID”选项卡。
  • 单击“新建应用程序 ID”按钮。
  • 指定说明和捆绑标识符(不应在捆绑标识符中使用 * )。
  • 单击“提交”。Provisioning Portal 会生成您的应用程序 ID 并重新显示“应用程序 ID”页面。
  • 单击“配置”(位于应用程序 ID右侧)。显示“配置应用程序 ID”页面。
  • 选择“启用 Apple 推送通知服务”复选框。注意有两种类型的推送 SSL 证书:一种用于开发/测试,一种用于生生产。
  • 单击“开发推送 SSL 证书”右侧的“配置”按钮。显示“生成证书签名请求 (CSR)”页面。
  • 按照页面所指示,使用 Keychain Access 公用程序生成 CSR。
  • 生成 SSL 证书。
  • 下载并安装 SSL 证书。
  • (可选)对于生产推送 SSL 证书重复第 9 步至第 12 步。
  • 单击“完成”。显示“配置应用程序 ID”页面。
  • 单击“完成”。显示“应用程序 ID”页面。注意应用程序 ID 的推送通知旁的绿色圆圈。
  • 确保保存 SSL 证书,因为该证书稍后将用于应用程序和提供方通信。
  • 单击“供给”选项卡以显示“供给配置文件”页面。
  • 为新的应用程序 ID 创建供给配置文件并下载。
  • 单击“证书”选项卡并为新的供给配置文件下载一个新的证书。



对推送通知使用声音。
要为应用程序启用声音通知,请将声音文件捆绑为其他任何资源,但在相同目录中捆绑为 SEF 和 app-xml 文件。例如:
Build/adt -package -target ipa-app-store -provisioning-profile _-_.mobileprovision -storetype pkcs12 -keystore _-_.p12 test.ipa test-app.xml test.swf sound.caf sound1.caf
Apple 支持以下声音数据格式(aiff、wav 或 caf 文件):
  • 线性 PCM
  • MA4 (IMA/ADPCM)
  • uLaw
  • aLaw



使用已本地化的警告通知
要在应用程序中使用已本地化的警告通知,请在 lproj 文件夹表单中捆绑已本地化的字符串。例如,您支持西班牙语的警告,则按以下步骤操作:
  • 在项目中创建与 app-xml 文件同级的 es.lproj 文件夹。
  • 在 es.lproj 文件夹中,创建一个名为 Localizable.Strings 的文本文件。
  • 在文本编辑器中打开 Localizable.Strings,并添加消息密钥和相应的已本地化字符串。例如:"PokeMessageFormat" = "La notificación de alertas en español."
  • 保存该文件。
  • 应用程序接收到使用该密钥值的警告通知且设备语言为西班牙语时,显示已译警告文本。




配置远程通知提供方
需要一个远程通知提供方以将推送通知发送至应用程序。此服务器应用程序用作提供方,接受推送输入,并将通知和通知数据传递至 APNs,然后 APNs 将推送通知发送至客户端应用程序。
关于来自远程通知提供方的推送通知的详细信息,请参阅 Apple 开发人员库中的提供方与 Apple 推送通知服务的通信


远程通知提供方选项
远程通知提供方选项包含以下内容:
  • 基于 APNS-php 开源服务器创建自己的提供方。可以使用 http://code.google.com/p/apns-php/ 建立 PHP 服务器。通过该 Google 代码项目,您可以设计一个与指定要求匹配的界面。
  • 使用服务提供方。例如,http://urbanairship.com/ 提供了一个现成的 APNs 提供方。注册该服务后,开始先使用与以下内容类似代码提供设备标记:
    1. private var urlreq:URLRequest;
    2. private var urlLoad:URLLoader = new URLLoader();
    3. private var urlString:String;

    4. //When subscription is successful then only call the following code
    5. urlString = new String("https://go.urbanairship.com/api/device_tokens/" + e.tokenId);
    6. urlreq = new URLRequest(urlString);

    7. urlreq.authenticate = true;
    8. urlreq.method = URLRequestMethod.PUT;
    9. URLRequestDefaults.setLoginCredentialsForHost("go.urbanairship.com",
    10.    "Application Key","Application Secret");
    11. urlLoad.load(urlreq);
    12. urlLoad.addEventListener(IOErrorEvent.IO_ERROR,iohandler);
    13. urlLoad.addEventListener(Event.COMPLETE,compHandler);
    14. urlLoad.addEventListener(HTTPStatusEvent.HTTP_STATUS,httpHandler);

    15. private function iohandler(e:IOErrorEvent):void{
    16.    trace("n In IOError handler" + e.errorID +" " +e.type);
    17. }

    18. private function compHandler(e:Event):void{
    19.    trace("n In Complete handler,"+"status: " +e.type + "n");
    20. }

    21. private function httpHandler(e:HTTPStatusEvent):void{
    22.    tt.appendText("n in httpstatus handler,"+ "Status: " + e.status);
    23. }
    复制代码
    • 然后您可以使用 Urban Airship 工具发送测试通知。




    远程通知提供方证书
    您必须复制 SSL 证书和私钥(之前生成的)至远程通知提供方服务器上适当的位置。通常将这两个文件组合至单个的 .pem 文件中。要进行此操作,请执行以下步骤:
    • 打开终端窗口。
    • 通过输入以下命令,从 SSL 证书创建 .pem 文件:
      1. openssl x509 -in aps_developer_identity.cer -inform der -out TestPushDev.pem
      复制代码

    • 通过输入以下命令,创建私钥 (.p12) 的 .pem 文件:
      1. openssl pkcs12 -nocerts -out TestPushPrivateKey.pem -in certificates.p12
      复制代码

    • 通过输入以下命令,将两个 .pem 文件组合至单个文件:
      1. cat TestPushDev.pem TestPushPrivateKey.pem > FinalTestPush.pem
      复制代码

      • 创建服务器端推送应用程序时,向服务器提供商提供组合的 .pem 文件。
      有关更多信息,请参阅 Apple 本机和推送通知编程指南中的在服务器中安装 SSL 证书和密钥




      在应用程序中处理推送通知
      在应用程序中处理推送通知涉及以下内容:
      • 推送通知的全局用户配置和接受
      • 单个推送通知的用户接受
      • 处理推送通知和通知有效载荷数据


      推送通知的配置和接受
      用户第一次启动启用推送通知的应用程序时,iOS 显示 appname 是否要给您发送推送通知对话框,对话框中包括“不允许”和“好”按钮。如果用户选择“好”,则应用程序会接收预定的所有类型的通知。如果用户选择“不允许”,则不会接收通知。
      注: 用户可以在“设置”>“通知”中控制可以为每个启用推送的应用程序接收的特定通知类型。
      Apple 建议每次激活应用程序时都应预定推送通知。应用程序调用 RemoteNotifier.subscribe() 时,会接收到 RemoteNotificationEvent,类型为 token,其包含唯一可以识别设备中应用程序的 32 字节唯一数字 tokenId。
      设备接收到推送通知时,显示一个弹出窗口,其中包括“关闭”和“启动”按钮。如果用户点击“关闭”,则没有事件发生;如果用户点击“启动”,则 iOS 会调用应用程序,且应用程序会接收到类型为 notification 的flash.events.RemoteNotificationEvent,如下所述。



      处理推送通知和有效载荷数据
      远程通知提供方将通知发送至设备(使用 tokenID)时,无论应用程序是否在运行中,应用程序都会接收到类型为 notification的 flash.events.RemoteNotificationEvent。此时,应用程序执行特定于应用程序的通知处理。如果应用程序处理通知数据,则可以通过 JSON 格式的 RemoteNotificationEvent.data 属性访问该数据。





















欢迎光临 守望者--AIR技术交流 (http://www.airmyth.com/)