- App Center Push
- Configuring App Center for Push Notifications
- Configuring Your Application for Push
- Device Registration
- Sending Push Notifications
- Настройка приложения для получения целевых push-уведомлений Configure your app for targeted push notifications
- Настройка проекта Configure your project
- Регистрация для получения push-уведомлений Register for push notifications
- Передача целевых push-уведомлений пользователям How targeted push notifications are routed to customers
- Реакция вашего приложения, когда его запускает пользователь How your app responds when the user launches your app
- Уведомление центра партнеров о запуске приложения Notify Partner Center of your app launch
- Отмена регистрации для получения push-уведомлений Unregister for push notifications
App Center Push
Note this feature is being retired. For more information, see the blog post. For more information, refer to the Push Migration Guide.
The Visual Studio App Center Push (ACP) service is a notification aggregation service, it manages the process of sending notifications to devices using Push Notification Services (PNS) from Apple, Google, and Microsoft. You could easily build your own application that does this for you:
- Managing the device registration process for each PNS
- Tracking device registration data (so you know how to send notifications to devices later)
- Building an application to send notifications through each PNS
- Tracking success (or failure) for notifications
App Center Push takes care of all that for you. Add the App Center SDK to an app, and on app start the SDK automatically registers the device for push notifications (with the appropriate PNS for the target device). With that in place, use the App Center Portal or its REST API to define audiences targeting app users, create campaigns, and send notifications to devices (and eventually users).
Configuring App Center for Push Notifications
Configuring Push for your application project is as simple as:
- Sign-up for a free App Center account at https://appcenter.ms.
- Create a new application project (what we call an App in App Center) or open an existing App project.
- Select the Push option in the project navigation pane.
- Configure any required settings for your app’s target platform. For example:
- Apple iOS devices use the Apple Push Notification service (APNs) to deliver notifications, you’ll have some configuration to do in APNs to enable Push in App Center.
- Google Android devices use the Firebase Cloud Messaging (FCM) service to deliver notifications, so you’ll have some configuration to do in FCM to enable Push in App Center.
- Windows devices use the Windows Notifications Services (WNS) to deliver notifications, so you’ll have some configuration to do in WNS to enable Push in App Center.
- Copy the appropriate notification service settings into your App Center App project.
For additional information, refer to Configuring the Push Service.
When Google announced deprecation of the Google Cloud Messaging service, we updated the SDK and backend to support this change. You shouldn’t have to make any changes to your app to support Google’s change. To learn more, refer to this Help Center article.
Configuring Your Application for Push
To configure your application to handle push notifications, you’ll add the App Center SDK to your application to manage device registration, then write the code needed to process notifications when they arrive. The instructions for doing this varies depending on the target platform. For additional information, refer to the App Center Push SDK platform documentation:
Device Registration
App Center Push can’t just push to any device. When a user runs your Push-enabled app for the first time after installation, the App Center Push SDK initializes and automatically registers the device running the application with the appropriate notification services. The SDK then provides App Center with the unique key (Install ID) it uses to send notifications to the device.
As you’ll see later, you can use the Install ID to send a notification to a specific device.
Sending Push Notifications
With the Push service configured, and devices running your application registered with the proper notification services, you’re ready to send notifications to devices. You can send notifications to devices two ways:
App Center supports the following notification targets:
- All registered devices: Sends notifications to all registered devices.
- Audiences: Sends notifications to a segment of your app’s registered device audience based on a set of device and custom properties.
- Custom device list: Sends notifications to up to 20 devices (using the install IDs for the target devices).
For additional information, refer to Sending Push Notifications.
Настройка приложения для получения целевых push-уведомлений Configure your app for targeted push notifications
Вы можете использовать страницу push-уведомлений в центре партнеров для непосредственного привлечения клиентов, отправляя целевые push-уведомления на устройства, на которых установлено приложение универсальная платформа Windows (UWP). You can use the Push notifications page in Partner Center to directly engage with customers by sending targeted push notifications to the devices on which your Universal Windows Platform (UWP) app is installed. Например, можно использовать целевые push-уведомления для побуждения пользователей к определенным действиям, таким как выставление оценки вашему приложению или использование новой функции. For example, you can use targeted push notifications to encourage your customers to take an action, such as rating your app or trying a new feature. Можно отправлять различные типы push-уведомлений, включая всплывающие уведомления, уведомления на плитках и необработанные уведомления XML. You can send several different types of push notifications, including toast notifications, tile notifications, and raw XML notifications. Также можно отслеживать количество запусков приложения, производимых из push-уведомлений. You can also track the rate of app launches that resulted from your push notifications. Дополнительные сведения об этой функции см. в разделе Отправка push-уведомлений пользователям вашего приложения. For more information about this feature, see Send push notifications to your app’s customers.
Прежде чем отправлять целевые push-уведомления клиентам из центра партнеров, необходимо использовать метод класса сторесервицесенгажементманажер в пакете SDK для служб Microsoft Store Services, чтобы зарегистрировать приложение для получения уведомлений. Before you can send targeted push notifications to your customers from Partner Center, you must use a method of the StoreServicesEngagementManager class in the Microsoft Store Services SDK to register your app to receive notifications. Вы можете использовать дополнительные методы этого класса для уведомления центра партнеров о том, что приложение было запущено в ответ на целевое push-уведомление (если вы хотите отчислить частоту запусков приложений, которые привели к вашим уведомлениям) и приступать к прекращению получения уведомлений. You can use additional methods of this class to notify Partner Center that your app was launched in response to a targeted push notification (if you want to track the rate of app launches that resulted from your notifications) and to stop receiving notifications.
Настройка проекта Configure your project
Прежде чем писать код, выполните следующие действия, чтобы добавить ссылку на Microsoft Store Services SDK в свой проект. Before you write any code, follow these steps to add a reference to the Microsoft Store Services SDK in your project:
- Если это еще не сделано, установите Microsoft Store Services SDK на компьютер разработки. If you have not done so already, Install the Microsoft Store Services SDK on your development computer.
- Откройте проект в Visual Studio. Open your project in Visual Studio.
- В обозревателе решений щелкните правой кнопкой мыши узел Ссылки вашего проекта и выберите команду Добавить ссылку . In Solution Explorer, right-click the References node for your project and click Add Reference .
- В диалоговом окне Диспетчер ссылок разверните список Универсальная платформа Windows и выберите Расширения . In Reference Manager , expand Universal Windows and click Extensions .
- В списке пакетов SDK установите флажок рядом с пунктом Microsoft Engagement Framework и нажмите кнопку ОК . In the list of SDKs, click the check box next to Microsoft Engagement Framework and click OK .
Регистрация для получения push-уведомлений Register for push notifications
Чтобы зарегистрировать приложение для получения целевых push-уведомлений из центра партнеров, выполните следующие действия. To register your app to receive targeted push notifications from Partner Center:
В своем проекте найдите раздел кода, выполняемого во время запуска, в котором можно зарегистрировать приложение для получения уведомлений. In your project, locate a section of code that runs during startup in which you can register your app to receive notifications.
Добавьте в начало файла с кодом следующее выражение: Add the following statement to the top of the code file.
Получите объект StoreServicesEngagementManager и вызовите один из перегруженных методов RegisterNotificationChannelAsync в коде запуска, определенном вами ранее. Get a StoreServicesEngagementManager object and call one of the RegisterNotificationChannelAsync overloads in the startup code you identified earlier. Этот метод следует вызывать каждый раз при запуске приложения. This method should be called each time that your app is launched.
Если вы хотите, чтобы центр партнеров самостоятельно создали собственный URI канала для уведомлений, вызовите перегрузку регистернотификатиончаннеласинк () . If you want Partner Center to create its own channel URI for the notifications, call the RegisterNotificationChannelAsync() overload.
Если ваше приложение также вызывает CreatePushNotificationChannelForApplicationAsync для создания канала уведомлений для WNS, убедитесь, что ваш код не вызывает CreatePushNotificationChannelForApplicationAsync и перегрузку RegisterNotificationChannelAsync() одновременно. If your app also calls CreatePushNotificationChannelForApplicationAsync to create a notification channel for WNS, make sure that your code does not call CreatePushNotificationChannelForApplicationAsync and the RegisterNotificationChannelAsync() overload simultaneously. Если необходимо вызвать оба этих метода, проследите за тем, чтобы они вызывались последовательно и дожидались возврата из одного метода перед вызовом второго. If you need to call both of these methods, make sure that you call them sequentially and await the return of one method before calling the other.
Если вы хотите указать URI канала, который будет использоваться для целевых push-уведомлений из центра партнеров, вызовите перегрузку регистернотификатиончаннеласинк (сторесервицеснотификатиончаннелпараметерс) . If you want to specify the channel URI to use for targeted push notifications from Partner Center, call the RegisterNotificationChannelAsync(StoreServicesNotificationChannelParameters) overload. Например, это может потребоваться, если ваше приложение уже использует службы push-уведомлений Windows (WNS) и вы хотите использовать один и тот же URI канала. For example, might want to do this if your app already uses Windows Push Notification Services (WNS) and you want to use the same channel URI. Сначала необходимо создать объект StoreServicesNotificationChannelParameters и назначить свойство CustomNotificationChannelUri вашему универсальному коду ресурса (URI) канала. You must first create a StoreServicesNotificationChannelParameters object and assign the CustomNotificationChannelUri property to your channel URI.
При вызове метода RegisterNotificationChannelAsync в локальном хранилище данных приложения создается файл с именем MicrosoftStoreEngagementSDKId.txt для вашего приложения (папка, возвращенная свойством ApplicationData.LocalFolder). When you call the RegisterNotificationChannelAsync method, a file named MicrosoftStoreEngagementSDKId.txt is created in the local app data store for your app (the folder returned by the ApplicationData.LocalFolder property). Этот файл содержит идентификатор, используемый инфраструктурой целевых push уведомлений. This file contains an ID that is used by the targeted push notifications infrastructure. Убедитесь, что ваше приложение не изменило или не удалило этот файл. Make sure that your app does not modify or delete this file. В противном случае ваши пользователи могут получать несколько экземпляров уведомлений, либо уведомления будут работать неправильно. Otherwise, your users may receive multiple instances of notifications, or the notifications may not behave properly in other ways.
Передача целевых push-уведомлений пользователям How targeted push notifications are routed to customers
Когда ваше приложение вызывает метод RegisterNotificationChannelAsync , этот метод получает информацию об учетной записи Майкрософт того пользователя, который в данный момент вошел на устройство. When your app calls RegisterNotificationChannelAsync , this method collects the Microsoft account of the customer who is currently signed in to the device. Позже при отправке целевого push-уведомления в сегмент, включающий этого клиента, центр партнеров отправляет уведомление на устройства, связанные с учетная запись Майкрософтом этого клиента. Later, when you send a targeted push notification to a segment that includes this customer, Partner Center sends the notification to devices that are associated with this customer’s Microsoft account.
Помните, что если пользователь, запустивший ваше приложение, передает свое устройство в пользование другому пользователю, то другой пользователь может увидеть уведомление, предназначенное первому пользователю, пока они находятся в системе под своими учетными записями Майкрософт. If the customer who started your app gives their device to someone else to use while they are still signed in to the device with their Microsoft account, be aware that the other person may see the notification that was targeted at the original customer. Это может привести к непредвиденным последствиям, особенно для приложений, предоставляющих услуги, которыми пользователь может воспользоваться, выполнив вход. This can have unintended consequences, particularly for apps that offer services that customers can sign in to use. В этом случае, чтобы запретить другим пользователям просматривать целевые уведомления, вызовите метод UnregisterNotificationChannelAsync, когда пользователи выйдут из вашего приложения. To prevent other users from seeing your targeted notifications in this scenario, call the UnregisterNotificationChannelAsync method when customers sign out of your app. Дополнительные сведения см. далее в разделе Отмена регистрации для получения push-уведомлений этой статьи. For more information, see Unregister for push notifications later in this article.
Реакция вашего приложения, когда его запускает пользователь How your app responds when the user launches your app
После регистрации приложения для получения уведомлений и отправки push-уведомлений клиентам вашего приложения из центра партнеров, одна из следующих точек входа в приложении будет вызываться, когда пользователь запускает приложение в ответ на push-уведомление. After your app is registered to receive notifications and you send a push notification to your app’s customers from Partner Center, one of the following entry points in your app will be called when the user launches your app in response to your push notification. Если у вас есть какой-либо код, который требуется выполнять, когда пользователь запускает ваше приложение, можно добавить этот код в одну из этих точек входа в приложении. If you have some code that you want to run when the user launches your app, you can add the code to one of these entry points in your app.
Если push-уведомление имеет тип активации переднего плана, переопределите метод OnActivated класса App в вашем проекте и добавьте свой код в этот метод. If the push notification has a foreground activation type, override the OnActivated method of the App class in your project and add your code to this method.
Если push-уведомление имеет фоновый тип активации, добавьте свой код в метод Run для фоновой задачи. If the push notification has a background activation type, add your code to the Run method for your background task.
Например, вы решите вознаграждать пользователей вашего приложения, которые приобрели какие-либо платные надстройки в приложении, путем предоставления им бесплатной надстройки. For example, you might want to reward the users of your app that have purchased any paid add-ons in your app by granting them a free add-on. В этом случае можно отправлять push-уведомление определенному сегменту пользователей, нацеленное на этих пользователей. In this case, you can send a push notification to a customer segment that targets these users. Затем можно добавить код, чтобы предоставить им право бесплатной покупки из приложения, в одну из перечисленных выше точек входа. Then, you can add code to grant them a free in-app purchase in one of the entry points listed above.
Уведомление центра партнеров о запуске приложения Notify Partner Center of your app launch
Если для целевого push-уведомления в центре партнеров выбран параметр » отвести курс запуска приложения «, вызовите метод парсеаргументсандтраккапплаунч из соответствующей точки входа в приложении, чтобы уведомить Центр партнеров о том, что приложение было запущено в ответ на push-уведомление. If you select the Track app launch rate option for your targeted push notification in Partner Center, call the ParseArgumentsAndTrackAppLaunch method from the appropriate entry point in your app to notify Partner Center that your app was launched in response to a push notification.
Этот метод также возвращает исходные аргументы запуска для приложения. This method also returns the original launch arguments for your app. Если вы решили отслеживать частоту запуска приложения для push-уведомлений, в аргументы запуска добавляется непрозрачный идентификатор отслеживания, помогающий отслеживать запуск приложения в центре партнеров. When you choose to track the app launch rate for your push notification, an opaque tracking ID is added to the launch arguments to help track the app launch in Partner Center. Необходимо передать аргументы запуска для приложения в метод парсеаргументсандтраккапплаунч , и этот метод отправляет идентификатор отслеживания в центр партнеров, удаляет идентификатор отслеживания из аргументов запуска и возвращает исходные аргументы запуска в код. You must pass the launch arguments for your app to the ParseArgumentsAndTrackAppLaunch method, and this method sends the tracking ID to Partner Center, removes the tracking ID from the launch arguments, and returns the original launch arguments to your code.
Способ вызова этого метода зависит от типа активации push-уведомления: The way you call this method depends on the activation type of the push notification:
Если push-уведомление имеет тип активации переднего плана, вызовите этот метод из переопределения метода OnActivated в своем приложении и передайте аргументы, доступные в объекте ToastNotificationActivatedEventArgs, передаваемом этому методу. If the push notification has a foreground activation type, call this method from the OnActivated method override in your app and pass the arguments that are available in the ToastNotificationActivatedEventArgs object that is passed to this method. В следующем примере кода предполагается, что файл кода содержит операторы using для пространств имен Microsoft.Services.Store.Engagement и Windows.ApplicationModel.Activation . The following code example assumes that your code file has using statements for the Microsoft.Services.Store.Engagement and Windows.ApplicationModel.Activation namespaces.
Если push-уведомление имеет фоновый тип активации, вызовите этот метод из метода Run вашей фоновой задачи и передайте аргументы, доступные в объекте ToastNotificationActionTriggerDetail, передаваемом этому методу. If the push notification has a background activation type, call this method from the Run method for your background task and pass the arguments that are available in the ToastNotificationActionTriggerDetail object that is passed to this method. В следующем примере кода предполагается, что ваш файл кода содержит операторы using для пространств имен Microsoft.Services.Store.Engagement , Windows.ApplicationModel.Background и Windows.UI.Notifications . The following code example assumes that your code file has using statements for the Microsoft.Services.Store.Engagement , Windows.ApplicationModel.Background , and Windows.UI.Notifications namespaces.
Отмена регистрации для получения push-уведомлений Unregister for push notifications
Если вы хотите, чтобы приложение перестает получать целевые push-уведомления от центра партнеров, вызовите метод унрегистернотификатиончаннеласинк . If you want your app to stop receiving targeted push notifications from Partner Center, call the UnregisterNotificationChannelAsync method.
Обратите внимание, что этот метод делает недействительным канал, который используется для уведомлений, поэтому приложение больше не будет получать push-уведомления ни от каких служб. Note that this method invalidates the channel that is being used for notifications so the app no longer receives push notifications from any services. После закрытия канал нельзя повторно использовать для любых служб, включая целевые push-уведомления из центра партнеров и других уведомлений, использующих WNS. After it has been closed, the channel cannot be used again for any services, including targeted push notifications from Partner Center and other notifications using WNS. Чтобы возобновить отправку push-уведомлений для этого приложения, приложение должно будет запросить новый канал. To resume sending push notifications to this app, the app must request a new channel.