通知中心入门(Kindle 应用)Get started with Notification Hubs for Kindle apps

本教程演示如何使用 Azure 通知中心将推送通知发送到 Kindle 应用程序。This tutorial shows you how to use Azure Notification Hubs to send push notifications to a Kindle application. 你将创建一个空白 Kindle 应用,它使用 Amazon Device Messaging (ADM) 接收推送通知。You create a blank Kindle app that receives push notifications by using Amazon Device Messaging (ADM).

在本教程中,你创建/更新代码来执行以下任务:In this tutorial, you create/update code to do the following tasks:

  • 向开发人员门户添加新应用程序Add a new app to the developer portal
  • 创建 API 密钥Create an API key
  • 创建并配置通知中心Create and configure a notification hub
  • 设置应用程序Set up your application
  • 创建 ADM 消息处理程序Create your ADM message handler
  • 将 API 密钥添加到应用Add your API key to your app
  • 运行应用程序Run the app
  • 发送测试通知Send a test notification

先决条件Prerequisites

向开发人员门户添加新应用程序Add a new app to the developer portal

  1. 登录到 Amazon 开发人员门户Sign into the Amazon Developer Portal.

  2. 依次选择“添加新应用”、“Android”。Select Add New App, and then select Android.

    “添加新应用”按钮

  3. 在“新建应用提交内容”页上,执行以下步骤获取应用程序密钥On the New App Submission page, follow these steps to get the application key:

    1. 输入“应用标题”的名称。Enter a name for the App title.

    2. 选择任一类别(例如“教育”)Select any category (for example: education)

    3. 在“客户支持电子邮件地址”字段中输入电子邮件地址。Enter an email address for the Customer support email address field.

    4. 选择“其他安全性验证” 。Select Save.

      “新建应用提交内容”页

  4. 在顶部切换到“手机广告”选项卡,然后执行以下步骤:At the top, switch to the Mobile Ads tab, and do the following steps:

    1. 指定你的应用是否主要面向 13 岁以下的儿童。Specify whether your app is directed primarily at kids under 13. 对于本教程,请选择“否”。For this tutorial, select No.

    2. 选择“提交”。Select Submit.

      “手动广告”页

    3. 复制“手机广告”页中的应用程序密钥Copy the application key from the Mobile Ads page.

      应用程序密钥

  5. 选择顶部的“应用和服务”菜单,然后在列表中选择你的应用程序。Select Apps & Services menu at the top, and select your application in the list.

    从列表中选择你的应用

  6. 切换到“设备消息传送”选项卡,然后执行以下步骤:Switch to the Device Messaging tab, and follow these steps:

    1. 选择“创建新的安全配置文件”。Select Create a New Security Profile.
    2. 输入安全配置文件的名称Enter a name for your security profile.
    3. 输入安全配置文件的说明Enter description for your security profile.
    4. 选择“其他安全性验证” 。Select Save.
    5. 在结果页上选择“查看安全配置文件”。Select View Security Profile on the result page.
  7. 现在,请在“安全配置文件”页上执行以下步骤:Now, on the Security Profile page, do the following steps:

    1. 切换到“Web 设置”选项卡,并复制“客户端 ID”和“客户端机密”值供稍后使用。Switch to the Web Settings tab, and copy the Client ID and Client Secret value for later use.

      获取客户端 ID 和机密

    2. 切换到“Android/Kindle 设置”页,并使该页保持打开状态。Switch to the Android/Kindle Settings page, and keep the page open. 将在下一部分输入这些值。You'll enter these values in the next section.

创建 API 密钥Create an API key

  1. 使用管理员特权打开命令提示符。Open a command prompt with administrator privileges.

  2. 导航到 Android SDK 文件夹。Navigate to the Android SDK folder.

  3. 输入以下命令:Enter the following command:

    keytool -list -v -alias androiddebugkey -keystore ./debug.keystore
    
  4. 对于“密钥存储”密码,请键入 android。For the keystore password, type android.

  5. 复制“MD5”和“SHA256”指纹。Copy the MD5 and SHA256 fingerprints.

  6. 返回开发人员门户,在“Android/Kindle 设置”选项卡上执行以下步骤:Back in the developer portal, on the Android/Kindle Settings tab, do the following steps:

    1. 输入 API 密钥的名称Enter a name for the API key.

    2. 输入应用的包名称(例如 com.fabrikam.mykindleapp)和“MD5”值。enter the name of the package for your app (for example, com.fabrikam.mykindleapp) and the MD5 value.

      Important

      在 Android Studio 中创建应用时,将使用此处指定的包名称。When you create an app in Android Studio, use the same package name you specified here.

    3. 粘贴前面复制的 MD5 签名Paste the MD5 signature you copied earlier.

    4. 粘贴前面复制的 SHA256 签名Paste the SHA256 signature you copied earlier.

    5. 选择“生成新密钥”。Select Generate New Key.

      Android/Kindle 设置 - 生成密钥

    6. 现在,请在列表中选择“显示”以查看 API 密钥。Now, select Show in the list to see the API key.

      Android/Kindle 设置 - 显示 API 密钥

    7. 在“API 密钥详细信息”窗口中,复制 API 密钥并将其保存到某个位置。In the API Key Details window, copy the API Key and save it somewhere. 然后,选择右上角的“X”以关闭窗口。Then, select X in the upper-right corner to close the window.

创建并配置通知中心Create and configure a notification hub

  1. 遵循在 Azure 门户中创建 Azure 通知中心一文中的步骤创建通知中心。Follow steps in the Create an Azure notification hub in the Azure portal article to create a notification hub.

  2. 在“设置”菜单下选择“Amazon (ADM)”。Select Amazon (ADM) under Settings menu.

  3. 粘贴前面保存的客户端 ID客户端机密Paste the Client ID and Client Secret you saved earlier.

  4. 在工具栏上选择“保存”。Select Save on the toolbar.

    配置通知中心的 ADM 设置

  5. 在左侧菜单中选择“访问策略”,然后选择 DefaultListenSharedAccessSignature 策略的连接字符串对应的“复制”按钮。Select Access Policies on the left menu, and select the copy button for the connection string for the DefaultListenSharedAccessSignature policy. 将其保存在某个位置。Save it somewhere. 稍后将在源代码中使用它。You'll use it later in the source code.

    通知中心 - 侦听连接字符串

设置应用程序Set up your application

  1. 启动 Android Studio。Launch Android Studio.

  2. 选择“文件”,指向“新建”,然后选择“新建项目”。Select File, point to New, and then select New Project.

  3. 在“选择项目”窗口中的“手机和平板电脑”选项卡上,依次选择“空活动”、“下一步”。In the Choose your project window, on the Phone and Tablet tab, select Empty Activity, and select Next.

  4. 在“配置项目”窗口中执行以下步骤:In the Configure your project window, do the following steps:

    1. 输入应用程序的名称Enter a name for your application. 建议使用与在 Amazon 开发人员门户中创建的应用程序名称匹配的名称。You may want to match it with the name of the application you created in the Amazon Developer Portal.

    2. 输入包的名称Enter a name for the package.

      Important

      该包名称必须与在 Amazon 开发人员门户中指定的包名称相匹配。The package name must match the package name you specified in the Amazon Developer Portal.

    3. 查看剩余的值并相应地更新。Review and update the remaining values as appropriate.

    4. 选择“完成”。Select Finish.

      配置 Android 项目

  5. 适用于 Android 的 Amazon 开发人员 SDK 库下载到硬盘。Download Amazon Developer SDK for Android library to your hard disk. 解压缩 SDK zip 文件。Extract the SDK zip file.

  6. 在 Android Studio 中,如果文件夹结构尚未设置为“项目”,请将其从“Android”更改为“项目”。In Android Studio, change the folder structure from Android to Project if it isn't already set to Project.

    Android Studio - 切换到项目结构

  7. 在树视图中展开 app 以查看 libs 文件夹。Expand app to see the libs folder in the tree view.

  8. 在“文件资源管理器”窗口中,导航到 Amazon Android SDK 所下载到的文件夹。In a File Explorer window, navigate to the folder where you downloaded the Amazon Android SDKs.

  9. 按住 CTRL 并将 amazon-device-messaging-1.0.1.jar 文件拖放到树视图中的 lib 节点。Press CTRL and drag-and-drop the amazon-device-messaging-1.0.1.jar file to the lib node in the tree view.

    Android Studio - 添加 Amazon Device Messaging JAR

  10. 在“复制”窗口中选择“确定”。In the Copy window, select OK. 如果看到的是“移动”窗口而不是“复制”窗口,请将其关闭,然后在按住 CTRL 按钮的同时重试拖放操作。If you see the Move window instead of Copy window, close it, and try drag-drop operation with CTRL button pressed.

    Android Studio - 复制 JAR

  11. 将以下语句添加到应用的 build.gradle 文件中的 dependencies 节:implementation files('libs/amazon-device-messaging-1.0.1.jar')Add the following statement to the app's build.gradle file in the dependencies section: implementation files('libs/amazon-device-messaging-1.0.1.jar').

    Android Studio - 将 ADM 添加到应用的 build.gradle

  12. 应用Build.Gradle 文件中的 dependencies 节内添加以下行:In the Build.Gradle file for the app, add the following lines in the dependencies section:

    implementation 'com.microsoft.azure:notification-hubs-android-sdk:0.6@aar'
    implementation 'com.microsoft.azure:azure-notifications-handler:1.0.1@aar'
    
  13. dependencies 节的后面添加以下存储库:Add the following repository after the dependencies section:

    repositories {
        maven {
            url "https://dl.bintray.com/microsoftazuremobile/SDK"
        }
    }
    
  14. 应用build.gradle 文件的编辑器中,选择工具栏上的“立即同步”。In the editor for the build.gradle file for the app, select Sync now on the toolbar.

    Android Studio - 同步应用的 build.gradle

  15. 切换回到树视图中的 Android 结构。Switch back to the Android structure in the tree view. 在根清单元素中添加 Amazon 命名空间:Add the Amazon namespace in the root manifest element:

    xmlns:amazon="http://schemas.amazon.com/apk/res/android"
    

    清单中的 Amazon 命名空间

  16. 在清单元素下添加权限作为第一个元素。Add permissions as the first element under the manifest element. [YOUR PACKAGE NAME] 替换为用于创建应用的包。Replace [YOUR PACKAGE NAME] with the package that you used to create your app.

    <permission
        android:name="[YOUR PACKAGE NAME].permission.RECEIVE_ADM_MESSAGE"
        android:protectionLevel="signature" />
    
    <uses-permission android:name="android.permission.INTERNET"/>
    
    <uses-permission android:name="[YOUR PACKAGE NAME].permission.RECEIVE_ADM_MESSAGE" />
    
    <!-- This permission allows your app access to receive push notifications
    from ADM. -->
    <uses-permission android:name="com.amazon.device.messaging.permission.RECEIVE" />
    
    <!-- ADM uses WAKE_LOCK to keep the processor from sleeping when a message is received. -->
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    
  17. 插入以下元素作为应用程序元素的第一个子级。Insert the following element as the first child of the application element. [YOUR PACKAGE NAME] 替换为用于创建应用的包名称。Replace [YOUR PACKAGE NAME] with the package name with which you created your app. 在下一步骤中将会创建 MyADMMessageHandler 类。You'll create the MyADMMessageHandler class in the next step.

        <amazon:enable-feature
            android:name="com.amazon.device.messaging"
            android:required="true"/>
        <service
            android:name="[YOUR PACKAGE NAME].MyADMMessageHandler"
            android:exported="false" />
        <receiver
            android:name="[YOUR PACKAGE NAME].MyADMMessageHandler$Receiver"
            android:permission="com.amazon.device.messaging.permission.SEND" >
    
            <!-- To interact with ADM, your app must listen for the following intents. -->
            <intent-filter>
                <action android:name="com.amazon.device.messaging.intent.REGISTRATION" />
                <action android:name="com.amazon.device.messaging.intent.RECEIVE" />
                <!-- Replace the name in the category tag with your app's package name. -->
                <category android:name="[YOUR PACKAGE NAME]" />
            </intent-filter>
        </receiver>
    

创建 ADM 消息处理程序Create your ADM message handler

  1. 将继承自 com.amazon.device.messaging.ADMMessageHandlerBase 的新类添加到项目中的 com.fabrikam.mykindleapp 包,并将其命名为 MyADMMessageHandler,如下图所示:Add a new class to the com.fabrikam.mykindleapp package in the project that inherits from com.amazon.device.messaging.ADMMessageHandlerBase and name it MyADMMessageHandler, as shown in the following image:

    创建 MyADMMessageHandler 类

  2. 将以下 import 语句添加到 MyADMMessageHandler 类:Add the following import statements to the MyADMMessageHandler class:

    import android.app.NotificationManager;
    import android.app.PendingIntent;
    import android.content.Context;
    import android.content.Intent;
    import android.support.v4.app.NotificationCompat;
    import android.util.Log;
    import com.amazon.device.messaging.ADMMessageReceiver;
    import com.microsoft.windowsazure.messaging.NotificationHub;
    
  3. 在创建的类中添加以下代码。Add the following code in the class that you created. 请记住包含通知中心和侦听连接字符串名称的 [HUB NAME][LISTEN CONNECTION STRING]Remember the [HUB NAME] and [LISTEN CONNECTION STRING] with the name of your notification hub and listen connection string:

    public static final int NOTIFICATION_ID = 1;
    private NotificationManager mNotificationManager;
    NotificationCompat.Builder builder;
    private static NotificationHub hub;
    
    public static NotificationHub getNotificationHub(Context context) {
        Log.v("com.wa.hellokindlefire", "getNotificationHub");
        if (hub == null) {
            hub = new NotificationHub("[HUB NAME]", "[HUB NAMESPACE CONNECTION STRING]", context);
        }
        return hub;
    }
    
    public MyADMMessageHandler() {
        super("MyADMMessageHandler");
    }
    
    @Override
    protected void onMessage(Intent intent) {
        String nhMessage = intent.getExtras().getString("msg");
        sendNotification(nhMessage);
    }
    
    @Override
    protected void onRegistrationError(String s) {
    
    }
    
    @Override
    protected void onRegistered(String s) {
        try {
            getNotificationHub(getApplicationContext()).register(s);
        } catch (Exception e) {
            Log.e("[your package name]", "Fail onRegister: " + e.getMessage(), e);
        }
    }
    
    @Override
    protected void onUnregistered(String s) {
        try {
            getNotificationHub(getApplicationContext()).unregister();
        } catch (Exception e) {
            Log.e("[your package name]", "Fail onUnregister: " + e.getMessage(), e);
        }
    }
    
    public static class Receiver extends ADMMessageReceiver
    {
        public Receiver()
        {
            super(MyADMMessageHandler.class);
        }
    }
    
    private void sendNotification(String msg) {
        Context ctx = getApplicationContext();
    
        mNotificationManager = (NotificationManager)
                ctx.getSystemService(Context.NOTIFICATION_SERVICE);
    
        PendingIntent contentIntent = PendingIntent.getActivity(ctx, 0,
                new Intent(ctx, MainActivity.class), 0);
    
    
        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(ctx)
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setContentTitle("Notification Hub Demo")
                        .setStyle(new NotificationCompat.BigTextStyle()
                                .bigText(msg))
                        .setContentText(msg);
    
        mBuilder.setContentIntent(contentIntent);
        mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
    }
    

将 API 密钥添加到应用Add your API key to your app

  1. 遵循以下步骤将 assets 文件夹添加到项目。Follow these steps to add an assets folder to the project.
    1. 切换到“项目”视图。Switch to the Project view.

    2. 右键单击“app”。Right-click app.

    3. 选择“新建”。Select New.

    4. 选择“文件夹”。Select Folder.

    5. 然后选择“Assets 文件夹”。Then, select Assets Folder.

      添加 assets 文件夹菜单

    6. 在“配置组件”页上执行以下步骤:On the Configure Component page, do the following steps:

      1. 选择“更改文件夹位置”Select Change folder location

      2. 确认文件夹已设置为:src/main/assetsConfirm that the folder is set to: src/main/assets.

      3. 选择“完成”。Select Finish.

        配置 assets 文件夹

  2. 将名为 api_key.txt 的文件添加到 assets 文件夹。Add a file named api_key.txt to the assets folder. 在树视图中,依次展开“app”、“src”、“main”,右键单击“assets”,指向“新建”,然后选择“文件”。In the tree view, expand app, expand src, expand main, and right-click assets, point to New, and then select File. 输入 api_key.txt 作为文件名。Enter api_key.txt for the file name. 3.3.
  3. 将你在 Amazon 开发人员门户中生成的 API 密钥复制到 api_key.txt 文件。Copy the API key that you generated in the Amazon developer portal to the api_key.txt file.
  4. 生成项目。Build the project.

运行应用程序Run the app

  1. 在 Kindle 设备上,从顶部往下轻扫,单击“设置”,然后单击“我的帐户”并使用有效的 Amazon 帐户注册。On the Kindle device, swipe from the top and click Settings, and then click My account and register with a valid Amazon account.
  2. 通过 Android Studio Kindle 在设备上运行该应用。Run the app on a Kindle device from Android Studio.

Note

如果出现了问题,请检查模拟器(或设备)的时间。If a problem occurs, check the time of the emulator (or device). 时间值必须准确。The time value must be accurate. 若要更改 Kindle 模拟器的时间,可以从 Android SDK platform-tools 目录运行以下命令:To change the time of the Kindle emulator, you can run the following command from your Android SDK platform-tools directory:

adb shell  date -s "yyyymmdd.hhmmss"

发送通知消息Send a notification message

若要使用 .NET 发送消息:To send a message by using .NET:

static void Main(string[] args)
{
    NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString("[conn string]", "[hub name]");

    hub.SendAdmNativeNotificationAsync("{\"data\":{\"msg\" : \"Hello from .NET!\"}}").Wait();
}

有关示例代码,请参阅 GitHub 上的此示例For sample code, see this example on GitHub.