Tutorial: Senden von Pushbenachrichtigungen an Android-Geräte mit Azure Notification Hubs und Google Cloud Messaging (veraltet)Tutorial: Send push notifications to Android devices by using Azure Notification Hubs and Google Cloud Messaging (deprecated)
Warnung
Seit dem 10. April 2018 wird Google Cloud Messaging (GCM) von Google nicht mehr unterstützt.As of April 10, 2018, Google has deprecated Google Cloud Messaging (GCM). Der GCM-Server und die Client-APIs sind veraltet und werden am 29. Mai 2019 entfernt.The GCM server and client APIs are deprecated and will be removed as soon as May 29, 2019. Weitere Informationen finden Sie unter GCM and FCM Frequently Asked Questions (Häufig gestellte Fragen zu GCM und FCM).For more information, see GCM and FCM Frequently Asked Questions.
ÜbersichtOverview
In diesem Tutorial erfahren Sie, wie Sie mithilfe von Azure Notification Hubs eine Pushbenachrichtigung an eine Android-App senden.This tutorial shows you how to use Azure Notification Hubs to send push notifications to an Android application. Sie erstellen eine leere Android-App, die Pushbenachrichtigungen mithilfe von Google Cloud Messaging (GCM) empfängt.You create a blank Android app that receives push notifications by using Google Cloud Messaging (GCM).
Wichtig
Google Cloud Messaging (GCM) ist veraltet und steht in Kürze nicht mehr zur Verfügung.The Google Cloud Messaging (GCM) is deprecated and will be removed soon.
Wichtig
In diesem Thema werden Pushbenachrichtigungen mit Google Cloud Messaging (GCM) veranschaulicht.This topic demonstrates push notifications with Google Cloud Messaging (GCM). Falls Sie Google Firebase Cloud Messaging (FCM) verwenden, helfen Ihnen die Informationen unter Sending push notifications to Android with Azure Notification Hubs and FCM(Senden von Pushbenachrichtigungen an Android mit Azure Notification Hubs und FCM) weiter.If you are using Google's Firebase Cloud Messaging (FCM), see Sending push notifications to Android with Azure Notification Hubs and FCM.
Den vollständigen Code für dieses Tutorial können Sie hierbei GitHub herunterladen.The completed code for this tutorial can be downloaded from GitHub here.
In diesem Tutorial führen Sie die folgenden Aktionen aus:In this tutorial, you do the following actions:
- Erstellen eines Projekts, das Google Cloud Messaging unterstütztCreate a project that supports Google Cloud Messaging.
- Erstellen eines Notification HubsCreate a notification hub
- Verbinden Ihrer App mit dem Notification HubConnect your app to the notification hub
- Testen der AppTest the app
VoraussetzungenPrerequisites
- Azure-Abonnement.Azure subscription. Falls Sie über kein Azure-Abonnement verfügen, können Sie ein kostenloses Azure-Konto erstellen, bevor Sie beginnen.If you don't have an Azure subscription, create a free Azure account before you begin.
- Android StudioAndroid Studio.
Erstellen eines Projekts, das Google Cloud Messaging unterstütztCreating a project that supports Google Cloud Messaging
Navigieren Sie zur Google Developers Console, und melden Sie sich mit den Anmeldeinformationen Ihres Google-Kontos an.Navigate to the Google Cloud Console, sign in with your Google account credentials.
Wählen Sie auf der Symbolleiste die Option Create Project (Projekt erstellen) aus.Select Create Project on the toolbar.
Geben Sie für Project name (Projektname) den Namen des Projekts ein, und klicken Sie auf Create (Erstellen).For Project name , enter a name for your project, and click Create.
Wählen Sie die Schaltfläche Alerts (Warnungen) auf der Symbolleiste aus, und wählen Sie das Projekt in der Liste aus.Select the alerts button on the toolbar, and select your project in the list. Das Dashboard für Ihr Projekt wird angezeigt.You see the dashboard for your project. Sie können auch mit der URL
https://console.developers.google.com/home/dashboard?project=<YOUR PROJECT NAME>
direkt zum Dashboard navigieren.You can also navigate directly to the dashboard by using the URL:https://console.developers.google.com/home/dashboard?project=<YOUR PROJECT NAME>
Notieren Sie sich die Project number (Projektnummer) in der Kachel Project info (Projektinformationen) des Dashboards.Note down the Project number in the Project info tile of the dashboard.
Wählen Sie im Dashboard auf der Kachel APIs die Option Go to APIs overview (Zur API-Übersicht wechseln) aus.In the dashboard, on the APIs tile, select Got to APIs overview.
Wählen Sie auf der API -Seite ENABLE APIS AND SERVICES (APIS UND DIENSTE AKTIVIEREN) aus.On the API page, select ENABLE APIS AND SERVICES.
Suchen Sie Google Cloud Messaging , und wählen Sie es aus.Search for and select Google Cloud Messaging.
Um Google Cloud Messaging für das Projekt zu aktivieren, wählen Sie AKTIVIEREN aus.To enable Google Cloud Messaging for the project, select ENABLE.
Wählen Sie Create credentials (Anmeldeinformationen erstellen) auf der Symbolleiste aus.Select Create credentials on the toolbar.
Wählen Sie auf der Seite Add credentials to your project (Anmeldeinformationen Ihrem Projekt hinzufügen) den Link API key (API-Schlüssel) aus.On the Add credentials to your project page, select API key link.
Wählen Sie auf der Seite API-Schlüssel die Option Create/Save (Erstellen/speichern) aus.On API key page, select Create/Save. Im folgenden Beispiel ist die Option IP addresses (IP-Adressen) ausgewählt, und 0.0.0.0/0 wird für zulässige IP-Adressen eingegeben.In the following example, the IP addresses option is selected, and 0.0.0.0/0 is entered for allowed IP addresses. Sie sollten Ihren API-Schlüssel entsprechend einschränken.You should restrict your API key appropriately.
Kopieren Sie den API-Schlüssel in die Zwischenablage, und speichern Sie ihn an beliebiger Stelle.Copy the API key to the clipboard, and save it somewhere.
Mit diesem API-Schlüsselwert geben Sie Azure die Möglichkeit, sich bei GCM zu authentifizieren und Pushbenachrichtigungen im Auftrag Ihrer App zu verschicken.You will use this API key value to enable Azure to authenticate with GCM and send push notifications on behalf of your app. Navigieren Sie mithilfe der URL
https://console.developers.google.com/home/dashboard?project=<YOUR PROJECT NAME>
zurück zum Projektdashboard.To navigate back to the project dashboard, use the URL:https://console.developers.google.com/home/dashboard?project=<YOUR PROJECT NAME>
Erstellen eines Notification HubsCreate a notification hub
Melden Sie sich beim Azure-Portal an.Sign in to the Azure portal.
Wählen Sie im Menü auf der linken Seite die Option Alle Dienste und dann im Abschnitt Mobil die Option Notification Hubs aus.Select All services on the left menu, and then select Notification Hubs in the Mobile section. Wählen Sie das Sternsymbol neben dem Dienstnamen aus, um den Dienst im linken Menü zum Abschnitt FAVORITEN hinzuzufügen.Select the star icon next to the service name to add the service to the FAVORITES section on the left menu. Nachdem Notification Hubs unter FAVORITEN hinzugefügt wurde, können Sie diesen Eintrag im Menü auf der linken Seite auswählen.After you add Notification Hubs to FAVORITES, select it on the left menu.
Wählen Sie auf der Seite Notification Hubs in der Symbolleiste die Option Hinzufügen.On the Notification Hubs page, select Add on the toolbar.
Führen Sie auf der Seite Notification Hub die folgenden Schritte aus:On the Notification Hub page, do the following steps:
Geben Sie ins Feld Notification Hub einen Namen ein.Enter a name in Notification Hub.
Geben Sie ins Feld Neuen Namespace erstellen einen Namen ein.Enter a name in Create a new namespace. Ein Namespace enthält mindestens einen Hub.A namespace contains one or more hubs.
Wählen Sie im Dropdown-Listenfeld Standort einen Wert aus.Select a value from the Location drop-down list box. Dieser Wert gibt den Standort an, an dem der Hub erstellt werden soll.This value specifies the location in which you want to create the hub.
Wählen Sie unter Ressourcengruppe eine vorhandene Ressourcengruppe aus, oder erstellen Sie einen Namen für eine neue Ressourcengruppe.Select an existing resource group in Resource Group, or create a name for a new resource group.
Klicken Sie auf Erstellen.Select Create.
Wählen Sie Benachrichtigungen (Glockensymbol) und dann Zu Ressource wechseln aus.Select Notifications (the bell icon), and then select Go to resource. Sie können auch die Liste auf der Seite Notification Hubs aktualisieren und Ihren Hub auswählen.You can also refresh the list on the Notification Hubs page and select your hub.
Wählen Sie in der Liste die Option Zugriffsrichtlinien aus.Select Access Policies from the list. Notieren Sie sich die beiden Verbindungszeichenfolgen, die für Sie verfügbar sind.Note that the two connection strings are available to you. Sie werden später für die Behandlung von Pushbenachrichtigungen benötigt.You'll need them later to handle push notifications.
Wichtig
Verwenden Sie nicht die Richtlinie DefaultFullSharedAccessSignature in Ihrer Anwendung.Do not use the DefaultFullSharedAccessSignature policy in your application. Diese ist nur für die Verwendung in Ihrem Back-End vorgesehen.This is meant to be used in your back end only.
Konfigurieren von GCM-Einstellungen für den BenachrichtigungshubConfigure GCM setting for the notification hub
Klicken Sie unter BENACHRICHTIGUNGSEINSTELLUNGEN auf Google (GCM) .Select Google (GCM) in NOTIFICATION SETTINGS.
Geben Sie den API-Schlüssel ein, den Sie aus Google Cloud Console abgerufen haben.Enter API Key you got from the Google Cloud Console.
Wählen Sie auf der Symbolleiste Speichern aus.Select Save on the toolbar.
Der Notification Hub ist jetzt für die Arbeit mit GCM konfiguriert, und Sie besitzen die Verbindungszeichenfolge, um die App für den Empfang und das Senden von Pushbenachrichtigungen zu registrieren.Your notification hub is now configured to work with GCM, and you have the connection strings to both register your app to receive and send push notifications.
Verbinden Ihrer App mit dem Notification HubConnect your app to the notification hub
Erstellen eines neuen Android-ProjektsCreate a new Android project
Starten Sie in Android Studio ein neues Android Studio-Projekt.In Android Studio, start a new Android Studio project.
Wählen Sie den Formfaktor Phone and Tablet und das Minimum SDK aus, das unterstützt werden soll.Choose the Phone and Tablet form factor and the Minimum SDK that you want to support. Klicken Sie dann auf Weiter.Then click Next.
Wählen Sie Empty Activity als Hauptaktivität aus, und klicken Sie auf Weiter und anschließend auf Fertig stellen.Choose Empty Activity for the main activity, click Next, and then click Finish.
Hinzufügen von Google Play Services zum ProjektAdd Google Play services to the project
Wählen Sie in Android Studio im Menü die Option Tools und dann SDK Manager aus.In Android Studio, select Tools on the menu, and then select SDK Manager.
Wählen Sie die Zielversion des Android SDK aus, das in Ihrem Projekt verwendet wird.Select the target version of the Android SDK that is used in your project. Wählen Sie dann Paketdetails anzeigen aus.Then select Show Package Details.
Wählen Sie die Option Google-APIs, falls diese Installation noch nicht durchgeführt wurde.Select Google APIs, if it's not already installed.
Wechseln Sie auf die Registerkarte SDK Tools (SDK-Tools). Wählen Sie wie in der folgenden Abbildung dargestellt die Option Google Play Services, falls Google Play Services noch nicht installiert ist.Switch to the SDK Tools tab. If you haven't already installed Google Play Services, select Google Play Services as shown in the following image. Wählen Sie dann Anwenden aus, um die Installation auszuführen.Then select Apply to install. Notieren Sie den SDK-Pfad, den Sie in einem späteren Schritt angeben müssen.Note the SDK path, for use in a later step.
Wählen Sie OK, wenn das Dialogfeld Änderung bestätigen angezeigt wird.If you see the Confirm Change dialog box, select OK. Die gewünschten Komponenten werden mit dem entsprechenden Installationsprogramm installiert.The Component Installer installs the requested components. Wählen Sie Fertig stellen, wenn die Installation der Komponenten abgeschlossen ist.Select Finish after the components are installed.
Wählen Sie OK, um das Dialogfeld Settings for New Projects (Einstellungen für neue Projekte) zu schließen.Select OK to close the Settings for New Projects dialog box.
Öffnen Sie die Datei „build.gradle“ im Verzeichnis app und fügen Sie dann die folgende Zeile unter
dependencies
hinzu.Open the build.gradle file in the app directory, and then add the following line underdependencies
.implementation 'com.google.android.gms:play-services-gcm:16.0.0'
Wählen Sie in der Symbolleiste das Symbol für Jetzt synchronisieren.Select Sync Now icon in the toolbar.
Öffnen Sie die Datei „AndroidManifest.xml“, und fügen Sie dann das folgende Tag zum Tag application hinzu.Open the AndroidManifest.xml file, and then add the following tag to the application tag.
<meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />
Hinzufügen von Azure Notification Hubs-BibliothekenAdding Azure Notification Hubs libraries
Fügen Sie in der Datei
Build.Gradle
für die App die folgenden Zeilen im Abschnitt dependencies hinzu.In theBuild.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'
Fügen Sie das folgende Repository nach dem Abschnitt dependencies hinzu.Add the following repository after the dependencies section.
repositories { maven { url "https://dl.bintray.com/microsoftazuremobile/SDK" } }
Aktualisieren Sie die Datei „AndroidManifest.xml“ des Projekts.Updating the project's AndroidManifest.xml
Für die Unterstützung von GCM müssen Sie im Code einen Instanz-ID-Listenerdienst implementieren, der zum Beschaffen von Registrierungstoken mit der Instanz-ID-API von Google verwendet wird.To support GCM, implement an Instance ID listener service in the code that is used to obtain registration tokens using Google's Instance ID API. In diesem Tutorial lautet der Name der Klasse
MyInstanceIDService
.In this tutorial, the name of the class isMyInstanceIDService
.Fügen Sie der Datei „AndroidManifest.xml“ im Tag
<application>
die unten angegebene Dienstdefinition hinzu.Add the following service definition to the AndroidManifest.xml file, inside the<application>
tag. Ersetzen Sie den Platzhalter<your package>
durch Ihren tatsächlichen Namen des Pakets, der oben in der DateiAndroidManifest.xml
angegeben ist.Replace the<your package>
placeholder with your actual package name shown at the top of theAndroidManifest.xml
file.<service android:name="<your package>.MyInstanceIDService" android:exported="false"> <intent-filter> <action android:name="com.google.android.gms.iid.InstanceID"/> </intent-filter> </service>
Nachdem die Anwendung das GCM-Registrierungstoken von der Instanz-ID-API erhalten hat, verwendet sie das Token zum Registrieren bei Azure Notification Hub.Once the application receives the GCM registration token from the Instance ID API, it uses the token to register with the Azure Notification Hub. Die Registrierung wird im Hintergrund mit einem
IntentService
-Element mit dem NamenRegistrationIntentService
unterstützt.The registration in the background is done using anIntentService
namedRegistrationIntentService
. Dieser Dienst ist für das Aktualisieren des GCM-Registrierungstokens zuständig.This service is responsible for refreshing the GCM registration token.Fügen Sie der Datei „AndroidManifest.xml“ im Tag
<application>
die unten angegebene Dienstdefinition hinzu.Add the following service definition to the AndroidManifest.xml file, inside the<application>
tag. Ersetzen Sie den Platzhalter<your package>
durch Ihren tatsächlichen Namen des Pakets, der oben in der DateiAndroidManifest.xml
angegeben ist.Replace the<your package>
placeholder with your actual package name shown at the top of theAndroidManifest.xml
file.<service android:name="<your package>.RegistrationIntentService" android:exported="false"> </service>
Definieren Sie einen Empfänger für die Benachrichtigungen.Define a receiver to receive notifications. Fügen Sie der Datei „AndroidManifest.xml“ im Tag
<application>
die unten angegebene Empfängerdefinition hinzu.Add the following receiver definition to the AndroidManifest.xml file, inside the<application>
tag. Ersetzen Sie den Platzhalter<your package>
durch Ihren tatsächlichen Namen des Pakets, der oben in der DateiAndroidManifest.xml
angegeben ist.Replace the<your package>
placeholder with your actual package name shown at the top of theAndroidManifest.xml
file.<receiver android:name="com.microsoft.windowsazure.notifications.NotificationsBroadcastReceiver" android:permission="com.google.android.c2dm.permission.SEND"> <intent-filter> <action android:name="com.google.android.c2dm.intent.RECEIVE" /> <category android:name="<your package name>" /> </intent-filter> </receiver>
Fügen Sie unterhalb des Tags
<application>
die folgenden erforderlichen GCM-bezogenen Berechtigungen hinzu.Add the following necessary GCM permissions below the<application>
tag. Ersetzen Sie dabei<your package>
durch den oben in der DateiAndroidManifest.xml
angegebenen Paketnamen.Replace<your package>
with the package name shown at the top of theAndroidManifest.xml
file.Weitere Informationen zu diesen Berechtigungen finden Sie unter Einrichten einer GCM-Client-App für Android.For more information on these permissions, see Set up a GCM Client app for Android.
<uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.GET_ACCOUNTS"/> <uses-permission android:name="android.permission.WAKE_LOCK"/> <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" /> <permission android:name="<your package>.permission.C2D_MESSAGE" android:protectionLevel="signature" /> <uses-permission android:name="<your package>.permission.C2D_MESSAGE"/>
Hinzufügen von CodeAdding code
Erweitern Sie in der Projektansicht die Knoten app > src > main > java.In the Project View, expand app > src > main > java. Klicken Sie mit der rechten Maustaste auf Ihren Paketordner unter java, klicken Sie auf Neu und dann auf Java Class.Right-click your package folder under java, click New, and then click Java Class. Fügen Sie eine neue Klasse namens
NotificationSettings
hinzu.Add a new class namedNotificationSettings
.Aktualisieren Sie die drei folgenden Platzhalter im weiter unten angegebenen Code für die
NotificationSettings
-Klasse:Update the three placeholders in the following code for theNotificationSettings
class:SenderId
: Dies ist die Projektnummer, die Sie zuvor über die Google Cloud Console abgerufen haben.SenderId
: The project number you obtained earlier in the Google Cloud Console.HubListenConnectionString
: Die DefaultListenAccessSignature-Verbindungszeichenfolge für Ihren Hub.HubListenConnectionString
: The DefaultListenAccessSignature connection string for your hub. Sie können diese Verbindungszeichenfolge kopieren, indem Sie im Azure portal auf der Seite Einstellungen Ihres Hub auf Zugriffsrichtlinien klicken.You can copy that connection string by clicking Access Policies on the Settings page of your hub on the Azure portal.HubName
: Verwenden Sie den Namen Ihres Benachrichtigungshubs, der im Azure portal auf der Hub-Seite angezeigt wird.HubName
: Use the name of your notification hub that appears in the hub page in the Azure portal.NotificationSettings
-Code:NotificationSettings
code:public class NotificationSettings { public static String SenderId = "<Your project number>"; public static String HubName = "<Your HubName>"; public static String HubListenConnectionString = "<Your default listen connection string>"; }
Fügen Sie eine weitere neue Klasse namens
MyInstanceIDService
hinzu.Add another new class namedMyInstanceIDService
. Diese Klasse ist die Implementierung des Instanz-ID-Listenerdiensts.This class is the Instance ID listener service implementation.Mit dem Code für diese Klasse wird Ihr
IntentService
-Element aufgerufen, um im Hintergrund das GCM-Token zu aktualisieren.The code for this class callsIntentService
to refresh the GCM token in the background.import android.content.Intent; import android.util.Log; import com.google.android.gms.iid.InstanceIDListenerService; public class MyInstanceIDService extends InstanceIDListenerService { private static final String TAG = "MyInstanceIDService"; @Override public void onTokenRefresh() { Log.i(TAG, "Refreshing GCM Registration Token"); Intent intent = new Intent(this, RegistrationIntentService.class); startService(intent); } };
Fügen Sie dem Projekt eine weitere neue Klasse namens
RegistrationIntentService
hinzu.Add another new class to your project, namedRegistrationIntentService
. Diese Klasse implementiertIntentService
zum Aktualisieren des GCM-Tokens und Registrieren beim Benachrichtigungshub.This class implementsIntentService
that handles refreshing the GCM token and registering with the notification hub.Verwenden Sie für diese Klasse den folgenden Code.Use the following code for this class.
import android.app.IntentService; import android.content.Intent; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.util.Log; import com.google.android.gms.gcm.GoogleCloudMessaging; import com.google.android.gms.iid.InstanceID; import com.microsoft.windowsazure.messaging.NotificationHub; public class RegistrationIntentService extends IntentService { private static final String TAG = "RegIntentService"; private NotificationHub hub; public RegistrationIntentService() { super(TAG); } @Override protected void onHandleIntent(Intent intent) { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); String resultString = null; String regID = null; try { InstanceID instanceID = InstanceID.getInstance(this); String token = instanceID.getToken(NotificationSettings.SenderId, GoogleCloudMessaging.INSTANCE_ID_SCOPE); Log.i(TAG, "Got GCM Registration Token: " + token); // Storing the registration id that indicates whether the generated token has been // sent to your server. If it is not stored, send the token to your server, // otherwise your server should have already received the token. if ((regID=sharedPreferences.getString("registrationID", null)) == null) { NotificationHub hub = new NotificationHub(NotificationSettings.HubName, NotificationSettings.HubListenConnectionString, this); Log.i(TAG, "Attempting to register with NH using token : " + token); regID = hub.register(token).getRegistrationId(); // If you want to use tags... // Refer to : https://azure.microsoft.com/documentation/articles/notification-hubs-routing-tag-expressions/ // regID = hub.register(token, "tag1", "tag2").getRegistrationId(); resultString = "Registered Successfully - RegId : " + regID; Log.i(TAG, resultString); sharedPreferences.edit().putString("registrationID", regID ).apply(); } else { resultString = "Previously Registered Successfully - RegId : " + regID; } } catch (Exception e) { Log.e(TAG, resultString="Failed to complete token refresh", e); // If an exception happens while fetching the new token or updating the registration data // on a third-party server, this ensures that we'll attempt the update at a later time. } // Notify UI that registration has completed. if (MainActivity.isVisible) { MainActivity.mainActivity.ToastNotify(resultString); } } }
Fügen Sie in der
MainActivity
-Klasse am Anfang der Klasse die folgendenimport
-Anweisungen hinzu.In yourMainActivity
class, add the followingimport
statements at the beginning of the class.import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GoogleApiAvailability; import com.google.android.gms.gcm.*; import com.microsoft.windowsazure.notifications.NotificationsManager; import android.util.Log; import android.widget.TextView; import android.widget.Toast; import android.content.Intent;
Fügen Sie folgende private Member oben in der Klasse hinzu.Add the following private members at the top of the class. Dieser Code überprüft die Verfügbarkeit von Google Play Services gemäß Empfehlung von Google.This code checks the availability of Google Play Services as recommended by Google.
public static MainActivity mainActivity; public static Boolean isVisible = false; private GoogleCloudMessaging gcm; private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000; private static final String TAG = "MainActivity";
Fügen Sie in der
MainActivity
-Klasse die folgende Methode zur Verfügbarkeit von Google Play Services hinzu.In yourMainActivity
class, add the following method to the availability of Google Play Services./** * Check the device to make sure it has the Google Play Services APK. If * it doesn't, display a dialog that allows users to download the APK from * the Google Play Store or enable it in the device's system settings. */ private boolean checkPlayServices() { GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance(); int resultCode = apiAvailability.isGooglePlayServicesAvailable(this); if (resultCode != ConnectionResult.SUCCESS) { if (apiAvailability.isUserResolvableError(resultCode)) { apiAvailability.getErrorDialog(this, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST) .show(); } else { Log.i(TAG, "This device is not supported by Google Play Services."); ToastNotify("This device is not supported by Google Play Services."); finish(); } return false; } return true; }
Fügen Sie in der
MainActivity
-Klasse den folgenden Code hinzu, mit dem eine Überprüfung auf Google Play Services durchgeführt wird, bevor dasIntentService
-Element aufgerufen wird, um Ihr GCM-Registrierungstoken abzurufen und die Registrierung beim Benachrichtungshub vorzunehmen.In yourMainActivity
class, add the following code that checks for Google Play Services before calling yourIntentService
to get your GCM registration token and register with your notification hub.public void registerWithNotificationHubs() { Log.i(TAG, " Registering with Notification Hubs"); if (checkPlayServices()) { // Start IntentService to register this application with GCM. Intent intent = new Intent(this, RegistrationIntentService.class); startService(intent); } }
Fügen Sie in der
OnCreate
-Methode derMainActivity
-Klasse den folgenden Code hinzu, um den Registrierungsprozess zu starten, wenn die Aktivität erstellt wird.In theOnCreate
method of theMainActivity
class, add the following code to start the registration process when activity is created.@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mainActivity = this; NotificationsManager.handleNotifications(this, NotificationSettings.SenderId, MyHandler.class); registerWithNotificationHubs(); }
Fügen Sie diese zusätzlichen Methoden dem
MainActivity
-Element hinzu, um den App-Zustand zu überprüfen und den Status in Ihrer App zu melden.Add these additional methods to theMainActivity
to verify app state and report status in your app.@Override protected void onStart() { super.onStart(); isVisible = true; } @Override protected void onPause() { super.onPause(); isVisible = false; } @Override protected void onResume() { super.onResume(); isVisible = true; } @Override protected void onStop() { super.onStop(); isVisible = false; } public void ToastNotify(final String notificationMessage) { runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(MainActivity.this, notificationMessage, Toast.LENGTH_LONG).show(); TextView helloText = (TextView) findViewById(R.id.text_hello); helloText.setText(notificationMessage); } }); }
Für die
ToastNotify
-Methode wird dasTextView
-Steuerelement „Hello World“ verwendet, um Status und Benachrichtigungen dauerhaft in der App zu melden.TheToastNotify
method uses the "Hello World"TextView
control to report status and notifications persistently in the app. Fügen Sie im Layout von „activity_main.xml“ die folgende ID für dieses Steuerelement hinzu.In your activity_main.xml layout, add the following ID for that control.android:id="@+id/text_hello"
Fügen Sie eine Unterklasse für den Empfänger hinzu, der in „AndroidManifest.xml“ definiert wurde.Add a subclass for the receiver that's defined in the AndroidManifest.xml. Fügen Sie dem Projekt eine weitere neue Klasse namens
MyHandler
hinzu.Add another new class to your project namedMyHandler
.Fügen Sie am Anfang von
MyHandler.java
die folgenden Importanweisungen hinzu:Add the following import statements at the top ofMyHandler.java
:import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.NotificationCompat; import com.microsoft.windowsazure.notifications.NotificationsHandler; import android.net.Uri; import android.media.RingtoneManager;
Fügen Sie für die
MyHandler
-Klasse den folgenden Code hinzu, um sie als Unterklasse voncom.microsoft.windowsazure.notifications.NotificationsHandler
festzulegen.Add the following code for theMyHandler
class, making it a subclass ofcom.microsoft.windowsazure.notifications.NotificationsHandler
.Mit diesem Code wird die
OnReceive
-Methode überschrieben, sodass der Handler empfangene Benachrichtigungen meldet.This code overrides theOnReceive
method, so the handler reports notifications that are received. Der Handler sendet die Pushbenachrichtigung mit dersendNotification()
-Methode auch an den Android-Benachrichtigungs-Manager.The handler also sends the push notification to the Android notification manager by using thesendNotification()
method. DiesendNotification()
-Methode muss ausgeführt werden, wenn die App nicht ausgeführt wird und eine Benachrichtigung eingeht.ThesendNotification()
method should be executed when the app is not running and a notification is received.public class MyHandler extends NotificationsHandler { public static final int NOTIFICATION_ID = 1; private NotificationManager mNotificationManager; NotificationCompat.Builder builder; Context ctx; @Override public void onReceive(Context context, Bundle bundle) { ctx = context; String nhMessage = bundle.getString("message"); sendNotification(nhMessage); if (MainActivity.isVisible) { MainActivity.mainActivity.ToastNotify(nhMessage); } } private void sendNotification(String msg) { Intent intent = new Intent(ctx, MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); mNotificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE); PendingIntent contentIntent = PendingIntent.getActivity(ctx, 0, intent, PendingIntent.FLAG_ONE_SHOT); Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(ctx) .setSmallIcon(R.mipmap.ic_launcher) .setContentTitle("Notification Hub Demo") .setStyle(new NotificationCompat.BigTextStyle() .bigText(msg)) .setSound(defaultSoundUri) .setContentText(msg); mBuilder.setContentIntent(contentIntent); mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build()); } }
Klicken Sie in Android Studio auf der Menüleiste auf Build > Rebuild Project, um sicherzustellen, dass im Code keine Fehler enthalten sind.In Android Studio on the menu bar, click Build > Rebuild Project to make sure that no errors are present in your code.
Testen der AppTesting your app
Ausführen der mobilen AnwendungRun the mobile application
Führen Sie die App aus, und prüfen Sie, ob die Registrierungs-ID als erfolgreiche Registrierung gemeldet wird.Run the app and notice that the registration ID is reported for a successful registration.
Geben Sie eine Benachrichtigungsmeldung ein, die an alle für den Hub registrierten Android-Geräte gesendet werden soll.Enter a notification message to be sent to all Android devices that have registered with the hub.
Tippen Sie auf Send Notification.Press Send Notification. Auf allen Geräten, auf denen die App ausgeführt wird, wird eine
AlertDialog
-Instanz mit der Pushbenachrichtigungsnachricht angezeigt.Any devices that have the app running shows anAlertDialog
instance with the push notification message. Geräte, auf denen die App nicht ausgeführt wird, die aber zuvor für Pushbenachrichtigungen registriert wurden, erhalten im Android-Benachrichtigungs-Manager eine Benachrichtigung.Devices that don't have the app running but were previously registered for push notifications receive a notification in the Android Notification Manager. Die Benachrichtigungsmeldungen können durch Wischen von der linken oberen Ecke nach unten angezeigt werden.The notification messages can be viewed by swiping down from the upper-left corner.
Senden von Test-Pushbenachrichtigungen im Azure-PortalTest send push notifications from the Azure portal
Sie können den Empfang von Pushbenachrichtigungen in Ihrer App testen, indem Sie sie über das Azure portal senden.You can test receiving push notifications in your app by sending them via the Azure portal.
Klicken Sie im Abschnitt Problembehandlung auf Testsendevorgang.In the Troubleshooting section, select Test Send.
Wählen Sie für Plattformen die Option Android aus.For Platforms, select Android.
Klicken Sie auf Senden, um die Testbenachrichtigung zu senden.Select Send to send the test notification.
Vergewissern Sie sich, dass die Benachrichtigungsmeldung auf dem Android-Gerät angezeigt wird.Confirm that you see the notification message on the Android device.
Pushbenachrichtigungen werden normalerweise mithilfe einer kompatiblen Bibliothek über einen Back-End-Dienst wie Mobile Apps oder ASP.NET gesendet.Push notifications are normally sent in a back-end service like Mobile Apps or ASP.NET using a compatible library. Falls für Ihr Back-End keine Bibliothek verfügbar ist, können Sie Benachrichtigungen auch direkt über die REST-API senden.If a library isn't available for your back end, you can also use the REST API directly to send notification messages.
Es folgen einige andere Tutorials, die Informationen zum Senden von Benachrichtigungen enthalten:Here is a list of some other tutorials you might want to review for sending notifications:
- Azure Mobile Apps: Ein Beispiel für das Senden von Benachrichtigungen von einem mit Notification Hubs integrierten Mobile Apps-Back-End finden Sie unter Hinzufügen von Pushbenachrichtigungen zu Ihrer iOS-App.Azure Mobile Apps: For an example of how to send notifications from a Mobile Apps back end integrated with Notification Hubs, see Add Push Notifications to your iOS App.
- ASP.NET: Verwenden von Notification Hubs für Pushbenachrichtigungen an BenutzerASP.NET: Use Notification Hubs to push notifications to users.
- Azure Notification Hub Java SDK: Informationen zum Senden von Benachrichtigungen über Java finden Sie unter Verwenden von Notification Hubs von Java aus.Azure Notification Hub Java SDK: See How to use Notification Hubs from Java for sending notifications from Java. Dies wurde für die Android-Entwicklung in Eclipse getestet.This has been tested in Eclipse for Android Development.
- PHP: Verwenden von Notification Hubs von PHP ausPHP: How to use Notification Hubs from PHP.
Pushbenachrichtigungen im EmulatorPush notifications in the emulator
Wenn Sie Pushbenachrichtigungen in einem Emulator testen möchten, müssen Sie sicherstellen, dass das Emulatorabbild die Google-API-Ebene unterstützt, die Sie für die App ausgewählt haben.If you want to test push notifications inside an emulator, make sure that your emulator image supports the Google API level that you chose for your app. Wenn das Image keine nativen Google-APIs unterstützt, wird die Ausnahme SERVICE_NOT_AVAILABLE ausgegeben.If your image doesn't support native Google APIs, you end up with the SERVICE_NOT_AVAILABLE exception.
Stellen Sie zusätzlich sicher, dass Ihr Google-Konto dem ausgeführten Emulator unter Einstellungen > Konten hinzugefügt wurde.In addition, ensure that you have added your Google account to your running emulator under Settings > Accounts. Andernfalls führt die Registrierung bei GCM möglicherweise zur Ausnahme AUTHENTICATION_FAILED.Otherwise, your attempts to register with GCM may result in the AUTHENTICATION_FAILED exception.
(Optional) Senden von Pushbenachrichtigungen direkt aus der App(Optional) Send push notifications directly from the app
In der Regel werden Benachrichtigungen über einen Back-End-Server versendet.Normally, you would send notifications using a backend server. In einigen Fällen ist es jedoch wünschenswert, wenn Sie Pushbenachrichtigungen direkt aus der Clientanwendung senden können.For some cases, you might want to be able to send push notifications directly from the client application. In diesem Abschnitt wird erläutert, wie Sie mithilfe der Azure Notification Hub-REST-APIBenachrichtigungen vom Client senden können.This section explains how to send notifications from the client using the Azure Notification Hub REST API.
Erweitern Sie in der Projektansicht von Android Studio App > src > main > res > layout.In Android Studio Project View, expand App > src > main > res > layout. Öffnen Sie die Layoutdatei
activity_main.xml
, und klicken Sie auf die Registerkarte Text, um den Textinhalt der Datei zu aktualisieren.Open theactivity_main.xml
layout file and click the Text tab to update the text contents of the file. Aktualisieren Sie ihn mit dem folgenden Code. Dadurch werden die neuen SteuerelementeButton
undEditText
hinzugefügt, um Nachrichten mit Pushbenachrichtigungen an den Notification Hub zu senden.Update it with the code below, which adds newButton
andEditText
controls for sending push notification messages to the notification hub. Fügen Sie diesen Code am Ende der Datei unmittelbar vor</RelativeLayout>
hinzu.Add this code at the bottom, just before</RelativeLayout>
.<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/send_button" android:id="@+id/sendbutton" android:layout_centerVertical="true" android:layout_centerHorizontal="true" android:onClick="sendNotificationButtonOnClick" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/editTextNotificationMessage" android:layout_above="@+id/sendbutton" android:layout_centerHorizontal="true" android:layout_marginBottom="42dp" android:hint="@string/notification_message_hint" />
Erweitern Sie in der Projektansicht von Android Studio App > src > main > res > values.In Android Studio Project View, expand App > src > main > res > values. Öffnen Sie die Datei
strings.xml
, und fügen Sie die Zeichenfolgenwerte hinzu, auf die von den neuen SteuerelementenButton
undEditText
verwiesen wird.Open thestrings.xml
file and add the string values that are referenced by the newButton
andEditText
controls. Fügen Sie die folgenden Zeilen am Ende der Datei unmittelbar vor</resources>
ein.Add the following lines at the bottom of the file, just before</resources>
.<string name="send_button">Send Notification</string> <string name="notification_message_hint">Enter notification message text</string>
Fügen Sie in der Datei
NotificationSetting.java
derNotificationSettings
-Klasse die folgende Einstellung hinzu.In yourNotificationSetting.java
file, add the following setting to theNotificationSettings
class.Aktualisieren Sie
HubFullAccess
mit der Verbindungszeichenfolge DefaultFullSharedAccessSignature für Ihren Hub.UpdateHubFullAccess
with the DefaultFullSharedAccessSignature connection string for your hub. Sie können diese Verbindungszeichenfolge aus dem Azure portal kopieren, indem Sie auf der Seite Einstellungen für den Benachrichtigungshub auf Zugriffsrichtlinien klicken.This connection string can be copied from the Azure portal by clicking Access Policies on the Settings page for your notification hub.public static String HubFullAccess = "<Enter Your DefaultFullSharedAccess Connection string>";
Fügen Sie in der Datei
MainActivity.java
am Anfang der Datei die folgendenimport
-Anweisungen hinzu.In yourMainActivity.java
file, add the followingimport
statements at the beginning of the file.import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import android.util.Base64; import android.view.View; import android.widget.EditText;
Fügen Sie in der Datei
MainActivity.java
im oberen Bereich derMainActivity
-Klasse die folgenden Member hinzu.In yourMainActivity.java
file, add the following members at the top of theMainActivity
class.private String HubEndpoint = null; private String HubSasKeyName = null; private String HubSasKeyValue = null;
Erstellen Sie ein SaS-Token (Shared Access Signature), um eine POST-Anforderung zum Senden von Nachrichten an den Benachrichtigungshub zu authentifizieren.Create a Shared Access Signature (SaS) token to authenticate a POST request to send messages to your notification hub. Analysieren Sie die wichtigsten Daten aus der Verbindungszeichenfolge, und erstellen Sie anschließend das SaS-Token (siehe dazu die REST-API-Referenz unter Allgemeine Konzepte).Parse the key data from the connection string and then creating the SaS token, as mentioned in the Common Concepts REST API reference. Der folgende Code ist ein Beispiel für eine Implementierung.The following code is an example implementation.
Fügen Sie der
MainActivity
-Klasse inMainActivity.java
die folgende Methode hinzu, um die Verbindungszeichenfolge zu analysieren.InMainActivity.java
, add the following method to theMainActivity
class to parse your connection string./** * Example code from https://msdn.microsoft.com/library/azure/dn495627.aspx * to parse the connection string so a SaS authentication token can be * constructed. * * @param connectionString This must be the DefaultFullSharedAccess connection * string for this example. */ private void ParseConnectionString(String connectionString) { String[] parts = connectionString.split(";"); if (parts.length != 3) throw new RuntimeException("Error parsing connection string: " + connectionString); for (int i = 0; i < parts.length; i++) { if (parts[i].startsWith("Endpoint")) { this.HubEndpoint = "https" + parts[i].substring(11); } else if (parts[i].startsWith("SharedAccessKeyName")) { this.HubSasKeyName = parts[i].substring(20); } else if (parts[i].startsWith("SharedAccessKey")) { this.HubSasKeyValue = parts[i].substring(16); } } }
Fügen Sie der
MainActivity
-Klasse inMainActivity.java
die folgende Methode hinzu, um ein SAS-Authentifizierungstoken zu erstellen.InMainActivity.java
, add the following method to theMainActivity
class to create a SaS authentication token./** * Example code from https://msdn.microsoft.com/library/azure/dn495627.aspx to * construct a SaS token from the access key to authenticate a request. * * @param uri The unencoded resource URI string for this operation. The resource * URI is the full URI of the Service Bus resource to which access is * claimed. For example, * "http://<namespace>.servicebus.windows.net/<hubName>" */ private String generateSasToken(String uri) { String targetUri; String token = null; try { targetUri = URLEncoder .encode(uri.toString().toLowerCase(), "UTF-8") .toLowerCase(); long expiresOnDate = System.currentTimeMillis(); int expiresInMins = 60; // 1 hour expiresOnDate += expiresInMins * 60 * 1000; long expires = expiresOnDate / 1000; String toSign = targetUri + "\n" + expires; // Get an hmac_sha1 key from the raw key bytes byte[] keyBytes = HubSasKeyValue.getBytes("UTF-8"); SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA256"); // Get an hmac_sha1 Mac instance and initialize with the signing key Mac mac = Mac.getInstance("HmacSHA256"); mac.init(signingKey); // Compute the hmac on input data bytes byte[] rawHmac = mac.doFinal(toSign.getBytes("UTF-8")); // Using android.util.Base64 for Android Studio instead of // Apache commons codec String signature = URLEncoder.encode( Base64.encodeToString(rawHmac, Base64.NO_WRAP).toString(), "UTF-8"); // Construct authorization string token = "SharedAccessSignature sr=" + targetUri + "&sig=" + signature + "&se=" + expires + "&skn=" + HubSasKeyName; } catch (Exception e) { if (isVisible) { ToastNotify("Exception Generating SaS : " + e.getMessage().toString()); } } return token; }
Fügen Sie der
MainActivity
-Klasse inMainActivity.java
die folgende Methode hinzu, um den Klick auf die Schaltfläche Benachrichtigung senden zu verarbeiten und die Nachricht mit der Pushbenachrichtigung über die integrierte REST-API an den Hub zu senden.InMainActivity.java
, add the following method to theMainActivity
class to handle the Send Notification button click and send the push notification message to the hub by using the built-in REST API./** * Send Notification button click handler. This method parses the * DefaultFullSharedAccess connection string and generates a SaS token. The * token is added to the Authorization header on the POST request to the * notification hub. The text in the editTextNotificationMessage control * is added as the JSON body for the request to add a GCM message to the hub. * * @param v */ public void sendNotificationButtonOnClick(View v) { EditText notificationText = (EditText) findViewById(R.id.editTextNotificationMessage); final String json = "{\"data\":{\"message\":\"" + notificationText.getText().toString() + "\"}}"; new Thread() { public void run() { try { // Based on reference documentation... // https://msdn.microsoft.com/library/azure/dn223273.aspx ParseConnectionString(NotificationSettings.HubFullAccess); URL url = new URL(HubEndpoint + NotificationSettings.HubName + "/messages/?api-version=2015-01"); HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection(); try { // POST request urlConnection.setDoOutput(true); // Authenticate the POST request with the SaS token urlConnection.setRequestProperty("Authorization", generateSasToken(url.toString())); // Notification format should be GCM urlConnection.setRequestProperty("ServiceBusNotification-Format", "gcm"); // Include any tags // Example below targets 3 specific tags // Refer to : https://azure.microsoft.com/documentation/articles/notification-hubs-routing-tag-expressions/ // urlConnection.setRequestProperty("ServiceBusNotification-Tags", // "tag1 || tag2 || tag3"); // Send notification message urlConnection.setFixedLengthStreamingMode(json.length()); OutputStream bodyStream = new BufferedOutputStream(urlConnection.getOutputStream()); bodyStream.write(json.getBytes()); bodyStream.close(); // Get response urlConnection.connect(); int responseCode = urlConnection.getResponseCode(); if ((responseCode != 200) && (responseCode != 201)) { BufferedReader br = new BufferedReader(new InputStreamReader((urlConnection.getErrorStream()))); String line; StringBuilder builder = new StringBuilder("Send Notification returned " + responseCode + " : ") ; while ((line = br.readLine()) != null) { builder.append(line); } ToastNotify(builder.toString()); } } finally { urlConnection.disconnect(); } } catch(Exception e) { if (isVisible) { ToastNotify("Exception Sending Notification : " + e.getMessage().toString()); } } } }.start(); }
Nächste SchritteNext steps
In diesem Tutorial haben Sie Broadcastbenachrichtigungen an alle Android-Geräte gesendet, die beim Back-End registriert sind.In this tutorial, you sent broadcast notifications to all your Android devices registered with the backend. Um zu erfahren, wie Sie Pushbenachrichtigungen an bestimmte Android-Geräte senden, fahren Sie mit dem folgenden Tutorial fort:To learn how to push notifications to specific Android devices, advance to the following tutorial: