Notitie
Voor toegang tot deze pagina is autorisatie vereist. U kunt proberen u aan te melden of de directory te wijzigen.
Voor toegang tot deze pagina is autorisatie vereist. U kunt proberen de mappen te wijzigen.
Overzicht
In deze zelfstudie voegt u pushmeldingen toe aan het quickstartproject Xamarin.Android , zodat een pushmelding naar het apparaat wordt verzonden telkens wanneer een record wordt ingevoegd.
Als u het gedownloade quickstart-serverproject niet gebruikt, hebt u het pushmeldingsuitbreidingspakket nodig. Zie de handleiding Werken met de .NET-back-endserver-SDK voor Azure Mobile Apps voor meer informatie.
Vereiste voorwaarden
Voor deze zelfstudie is de installatie vereist:
- Een actief Google-account. U kunt zich registreren voor een Google-account op accounts.google.com.
- Google Cloud Messaging-clientonderdeel.
Een Notification Hub configureren
De functie Mobile Apps van Azure App Service maakt gebruik van Azure Notification Hubs om pushes te verzenden, zodat u een Notification Hub configureert voor uw mobiele app.
Ga in de Azure Portalnaar App Services-en selecteer vervolgens de back-end van uw app. Selecteer onder Instellingende optie Push.
Om een meldingshubbron aan de app toe te voegen, selecteert u Verbinding maken. U kunt een hub maken of verbinding maken met een bestaande hub.
U hebt nu een Notification Hub verbonden met uw back-endproject voor Mobiele apps. Later configureert u deze Notification Hub om verbinding te maken met een platformmeldingssysteem (PNS) om naar apparaten te pushen.
Firebase Cloud Messaging inschakelen
Meld u aan bij de Firebase-console. Maak een nieuw Firebase-project als u er nog geen hebt.
Nadat u uw project hebt gemaakt, selecteert u Firebase toevoegen aan uw Android-app.
Voer de volgende stappen uit op de pagina Firebase toevoegen aan uw Android-app:
Voor Android-pakketnaam kopieert u de waarde van uw applicationId in het bestand build.gradle van uw toepassing. In dit voorbeeld is het
com.fabrikam.fcmtutorial1app.
Selecteer App registreren.
Selecteer google-services.json downloaden, sla het bestand op in de map app van uw project, en selecteer Volgende.
Breng de volgende configuratiewijzigingen aan in uw project in Android Studio.
Voeg in het bestand build.gradle op projectniveau (<project>/build.gradle) de volgende instructie toe aan de sectie dependencies (afhankelijkheden).
classpath 'com.google.gms:google-services:4.0.1'Voeg in het build.gradle-bestand op app-niveau (<project>/<app-module>/build.gradle) de volgende instructies toe aan de sectie afhankelijkheden .
implementation 'com.google.firebase:firebase-core:16.0.8' implementation 'com.google.firebase:firebase-messaging:17.3.4'Voeg de volgende regel toe aan het einde van het build.gradle-bestand op app-niveau na de sectie met afhankelijkheden.
apply plugin: 'com.google.gms.google-services'Selecteer Nu synchroniseren op de werkbalk.
Kies Volgende.
Selecteer Deze stap overslaan.
Selecteer in de Firebase-console het tandwiel van uw project. Selecteer vervolgens Projectinstellingen.
Als u het bestand google-services.json niet hebt gedownload in de map app van uw Android Studio-project, kunt u dat op deze pagina doen.
Ga naar Cloud Messaging bovenaan op het tabblad.
Kopieer de Serversleutel en sla deze op voor later gebruik. U gebruikt deze waarde om uw hub te configureren.
Azure configureren voor het verzenden van pushaanvragen
Klik in het Azure-portaalop Browse All>App Servicesen klik vervolgens op de back-end van je mobiele apps. Klik onder Instellingenop App Service Push-en klik vervolgens op de naam van de Notification Hub.
Ga naar Google (GCM), voer de serversleutel waarde in die u in de vorige procedure hebt verkregen bij Firebase en klik vervolgens op Opslaan.
De back-end van Mobile Apps is nu geconfigureerd voor het gebruik van Firebase Cloud Messaging. Hiermee kunt u pushmeldingen verzenden naar uw app die wordt uitgevoerd op een Android-apparaat met behulp van de Notification Hub.
Het serverproject bijwerken om pushmeldingen te verzenden
In deze sectie werkt u code bij in uw bestaande back-endproject voor mobiele apps om telkens wanneer een nieuw item wordt toegevoegd, een pushmelding te verzenden. Dit proces wordt mogelijk gemaakt door de sjabloon functie van Azure Notification Hubs, waardoor platformoverschrijdende pushes mogelijk zijn. De verschillende clients worden geregistreerd voor pushmeldingen met behulp van sjablonen en één universele push kan naar alle clientplatforms worden verzonden.
Kies een van de volgende procedures die overeenkomen met het type back-endproject: .NET-back-end of Node.js back-end.
.NET back-end project
Klik in Visual Studio met de rechtermuisknop op het serverproject. Selecteer vervolgens NuGet-pakketten beheren. Zoek naar
Microsoft.Azure.NotificationHubs, en selecteer vervolgens Installeren. Met dit proces wordt de Notification Hubs-bibliotheek geïnstalleerd voor het verzenden van meldingen vanaf de back-end.In het serverproject, open Controllers>TodoItemController.cs. Voeg vervolgens het volgende toe met behulp van instructies:
using System.Collections.Generic; using Microsoft.Azure.NotificationHubs; using Microsoft.Azure.Mobile.Server.Config;Voeg in de methode PostTodoItem de volgende code toe na de aanroep naar InsertAsync-:
// Get the settings for the server project. HttpConfiguration config = this.Configuration; MobileAppSettingsDictionary settings = this.Configuration.GetMobileAppSettingsProvider().GetMobileAppSettings(); // Get the Notification Hubs credentials for the mobile app. string notificationHubName = settings.NotificationHubName; string notificationHubConnection = settings .Connections[MobileAppSettingsKeys.NotificationHubConnectionString].ConnectionString; // Create a new Notification Hub client. NotificationHubClient hub = NotificationHubClient .CreateClientFromConnectionString(notificationHubConnection, notificationHubName); // Send the message so that all template registrations that contain "messageParam" // receive the notifications. This includes APNS, GCM, WNS, and MPNS template registrations. Dictionary<string,string> templateParams = new Dictionary<string,string>(); templateParams["messageParam"] = item.Text + " was added to the list."; try { // Send the push notification and log the results. var result = await hub.SendTemplateNotificationAsync(templateParams); // Write the success result to the logs. config.Services.GetTraceWriter().Info(result.State.ToString()); } catch (System.Exception ex) { // Write the failure result to the logs. config.Services.GetTraceWriter() .Error(ex.Message, null, "Push.SendAsync Error"); }Met dit proces wordt een sjabloonmelding met het item verzonden. Tekst wanneer een nieuw item wordt ingevoegd.
Publiceer het serverproject opnieuw.
Node.js back-end project
Stel uw back-endproject in.
Vervang de bestaande code in todoitem.js door de volgende code:
var azureMobileApps = require('azure-mobile-apps'), promises = require('azure-mobile-apps/src/utilities/promises'), logger = require('azure-mobile-apps/src/logger'); var table = azureMobileApps.table(); table.insert(function (context) { // For more information about the Notification Hubs JavaScript SDK, // see https://aka.ms/nodejshubs. logger.info('Running TodoItem.insert'); // Define the template payload. var payload = '{"messageParam": "' + context.item.text + '" }'; // Execute the insert. The insert returns the results as a promise. // Do the push as a post-execute action within the promise flow. return context.execute() .then(function (results) { // Only do the push if configured. if (context.push) { // Send a template notification. context.push.send(null, payload, function (error) { if (error) { logger.error('Error while sending push notification: ', error); } else { logger.info('Push notification sent successfully!'); } }); } // Don't forget to return the results from the context.execute(). return results; }) .catch(function (error) { logger.error('Error while running context.execute: ', error); }); }); module.exports = table;Met dit proces wordt een sjabloonmelding met de item.text verzonden wanneer een nieuw item wordt ingevoegd.
Wanneer u het bestand op uw lokale computer bewerkt, publiceert u het serverproject opnieuw.
Het clientproject configureren voor pushmeldingen
Klik in de oplossingsweergave (of Solution Explorer in Visual Studio) met de rechtermuisknop op de map Onderdelen , klik op Meer onderdelen ophalen..., zoek naar het google Cloud Messaging-clientonderdeel en voeg het toe aan het project.
Open het ToDoActivity.cs projectbestand en voeg de volgende using-instructie toe aan de klasse:
using Gcm.Client;Voeg in de klasse ToDoActivity de volgende nieuwe code toe:
// Create a new instance field for this activity. static ToDoActivity instance = new ToDoActivity(); // Return the current activity instance. public static ToDoActivity CurrentActivity { get { return instance; } } // Return the Mobile Services client. public MobileServiceClient CurrentClient { get { return client; } }Hiermee hebt u toegang tot de mobiele clientinstanties vanuit het push-handler serviceproces.
Voeg de volgende code toe aan de OnCreate-methode nadat de MobileServiceClient is gemaakt:
// Set the current instance of TodoActivity. instance = this; // Make sure the GCM client is set up correctly. GcmClient.CheckDevice(this); GcmClient.CheckManifest(this); // Register the app for push notifications. GcmClient.Register(this, ToDoBroadcastReceiver.senderIDs);
Uw ToDoActivity is nu voorbereid voor het toevoegen van pushmeldingen.
Code voor pushmeldingen toevoegen aan uw app
Maak een nieuwe klasse in het project met de naam
ToDoBroadcastReceiver.Voeg de volgende using-instructies toe aan de klasse ToDoBroadcastReceiver :
using Gcm.Client; using Microsoft.WindowsAzure.MobileServices; using Newtonsoft.Json.Linq;Voeg de volgende machtigingsaanvragen toe tussen de using-instructies en de naamruimtedeclaratie :
[assembly: Permission(Name = "@PACKAGE_NAME@.permission.C2D_MESSAGE")] [assembly: UsesPermission(Name = "@PACKAGE_NAME@.permission.C2D_MESSAGE")] [assembly: UsesPermission(Name = "com.google.android.c2dm.permission.RECEIVE")] //GET_ACCOUNTS is only needed for android versions 4.0.3 and below [assembly: UsesPermission(Name = "android.permission.GET_ACCOUNTS")] [assembly: UsesPermission(Name = "android.permission.INTERNET")] [assembly: UsesPermission(Name = "android.permission.WAKE_LOCK")]Vervang de bestaande ToDoBroadcastReceiver-klassedefinitie door het volgende:
[BroadcastReceiver(Permission = Gcm.Client.Constants.PERMISSION_GCM_INTENTS)] [IntentFilter(new string[] { Gcm.Client.Constants.INTENT_FROM_GCM_MESSAGE }, Categories = new string[] { "@PACKAGE_NAME@" })] [IntentFilter(new string[] { Gcm.Client.Constants.INTENT_FROM_GCM_REGISTRATION_CALLBACK }, Categories = new string[] { "@PACKAGE_NAME@" })] [IntentFilter(new string[] { Gcm.Client.Constants.INTENT_FROM_GCM_LIBRARY_RETRY }, Categories = new string[] { "@PACKAGE_NAME@" })] public class ToDoBroadcastReceiver : GcmBroadcastReceiverBase<PushHandlerService> { // Set the Google app ID. public static string[] senderIDs = new string[] { "<PROJECT_NUMBER>" }; }In de bovenstaande code moet u
<PROJECT_NUMBER>vervangen door het projectnummer dat door Google is toegewezen bij het provisioneren van uw app in de Google-ontwikkelaarsportal.Voeg in het ToDoBroadcastReceiver.cs projectbestand de volgende code toe waarmee de klasse PushHandlerService wordt gedefinieerd:
// The ServiceAttribute must be applied to the class. [Service] public class PushHandlerService : GcmServiceBase { public static string RegistrationID { get; private set; } public PushHandlerService() : base(ToDoBroadcastReceiver.senderIDs) { } }Houd er rekening mee dat deze klasse is afgeleid van GcmServiceBase en dat het servicekenmerk moet worden toegepast op deze klasse.
Opmerking
De klasse GcmServiceBase implementeert de methoden OnRegistered(), OnUnRegistered(), OnMessage() en OnError(). U moet deze methoden overschrijven in de klasse PushHandlerService .
Voeg de volgende code toe aan de klasse PushHandlerService die de gebeurtenis-handler OnRegistered overschrijft.
protected override void OnRegistered(Context context, string registrationId) { System.Diagnostics.Debug.WriteLine("The device has been registered with GCM.", "Success!"); // Get the MobileServiceClient from the current activity instance. MobileServiceClient client = ToDoActivity.CurrentActivity.CurrentClient; var push = client.GetPush(); // Define a message body for GCM. const string templateBodyGCM = "{\"data\":{\"message\":\"$(messageParam)\"}}"; // Define the template registration as JSON. JObject templates = new JObject(); templates["genericMessage"] = new JObject { {"body", templateBodyGCM } }; try { // Make sure we run the registration on the same thread as the activity, // to avoid threading errors. ToDoActivity.CurrentActivity.RunOnUiThread( // Register the template with Notification Hubs. async () => await push.RegisterAsync(registrationId, templates)); System.Diagnostics.Debug.WriteLine( string.Format("Push Installation Id", push.InstallationId.ToString())); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine( string.Format("Error with Azure push registration: {0}", ex.Message)); } }Deze methode gebruikt de geretourneerde GCM-registratie-id om u te registreren bij Azure voor pushmeldingen. Tags kunnen alleen worden toegevoegd aan de registratie nadat deze is gemaakt. Voor meer informatie, zie Hoe tags toe te voegen aan een apparaatinstallatie voor het inschakelen van push-naar-tags.
Overschrijf de OnMessage-methode in PushHandlerService met de volgende code:
protected override void OnMessage(Context context, Intent intent) { string message = string.Empty; // Extract the push notification message from the intent. if (intent.Extras.ContainsKey("message")) { message = intent.Extras.Get("message").ToString(); var title = "New item added:"; // Create a notification manager to send the notification. var notificationManager = GetSystemService(Context.NotificationService) as NotificationManager; // Create a new intent to show the notification in the UI. PendingIntent contentIntent = PendingIntent.GetActivity(context, 0, new Intent(this, typeof(ToDoActivity)), 0); // Create the notification using the builder. var builder = new Notification.Builder(context); builder.SetAutoCancel(true); builder.SetContentTitle(title); builder.SetContentText(message); builder.SetSmallIcon(Resource.Drawable.ic_launcher); builder.SetContentIntent(contentIntent); var notification = builder.Build(); // Display the notification in the Notifications Area. notificationManager.Notify(1, notification); } }Overschrijf de methoden OnUnRegistered() en OnError() met de volgende code.
protected override void OnUnRegistered(Context context, string registrationId) { throw new NotImplementedException(); } protected override void OnError(Context context, string errorId) { System.Diagnostics.Debug.WriteLine( string.Format("Error occurred in the notification: {0}.", errorId)); }
Pushmeldingen testen in uw app
U kunt de app testen met behulp van een virtueel apparaat in de emulator. Er zijn extra configuratiestappen vereist bij het uitvoeren op een emulator.
Op het virtuele apparaat moeten Google-API's als doel zijn ingesteld in de AVD-beheerder (Android Virtual Device).

Voeg een Google-account toe aan het Android-apparaat door opApps-instellingen>>account toevoegen te klikken en volg de aanwijzingen.

Voer de takenlijst-app uit zoals eerder en voeg een nieuwe taak in. In het systeemvak wordt deze keer een meldingspictogram weergegeven. U kunt de meldingslade openen om de volledige tekst van de melding weer te geven.
