Självstudie: skicka push-meddelanden till Android-enheter med Firebase SDK version 0,6Tutorial: Send push notifications to Android devices using Firebase SDK version 0.6
Den här självstudien visar hur du använder Azure Notification Hubs och Firebase Cloud Messaging (FCM) SDK version 0,6 för att skicka push-meddelanden till ett Android-program.This tutorial shows you how to use Azure Notification Hubs and the Firebase Cloud Messaging (FCM) SDK version 0.6 to send push notifications to an Android application. I den här självstudien skapar du en tom Android-app som tar emot push-meddelanden via Firebase Cloud Messaging (FCM).In this tutorial, you create a blank Android app that receives push notifications by using Firebase Cloud Messaging (FCM).
Den färdiga koden för den här självstudien kan laddas ned från GitHub.The completed code for this tutorial can be downloaded from GitHub.
I den här självstudien gör du följande:In this tutorial, you take the following steps:
- Skapa ett Android Studio-projekt.Create an Android Studio project.
- Skapa ett Firebase-projekt som har stöd för Firebase Cloud Messaging.Create a Firebase project that supports Firebase Cloud Messaging.
- Skapa en hubb.Create a hub.
- Anslut din app till hubben.Connect your app to the hub.
- Testa appen.Test the app.
FörutsättningarPrerequisites
Du måste ha ett aktivt Azure-konto för att slutföra den här kursen.To complete this tutorial, you must have an active Azure account. Om du inte har något konto kan skapa du ett kostnadsfritt utvärderingskonto på bara några minuter.If you don't have an account, you can create a free trial account in just a couple of minutes. Mer information om den kostnadsfria utvärderingsversionen av Azure finns Kostnadsfri utvärderingsversion av Azure.For details, see Azure Free Trial.
Du behöver också följande objekt:You also need the following items:
- Den senaste versionen av Android StudioThe latest version of Android Studio
- Android 2,3 eller högre för Firebase Cloud MessagingAndroid 2.3 or higher for Firebase Cloud Messaging
- Google databas revision 27 eller högre för Firebase Cloud MessagingGoogle Repository revision 27 or higher for Firebase Cloud Messaging
- Google Play Services 9.0.2 eller senare för Firebase Cloud MessagingGoogle Play Services 9.0.2 or higher for Firebase Cloud Messaging
Du måste slutföra den här själv studie kursen för att göra alla andra Notification Hubs själv studie kurser för Android-appar.Completing this tutorial is a prerequisite for doing all other Notification Hubs tutorials for Android apps.
Skapa ett Android Studio-projektCreate an Android Studio Project
- Starta Android Studio.Launch Android Studio.
- Välj fil, peka på nytt och välj sedan nytt projekt.Select File, point to New, and then select New Project.
- På sidan Välj ditt projekt väljer du Tom aktivitet och väljer sedan Nästa.On the Choose your project page, select Empty Activity, and then select Next.
- Utför följande steg på sidan Konfigurera ditt projekt :On the Configure your project page, take the following steps:
Ange ett namn på programmet.Enter a name for the application.
Ange en plats där du vill spara projektfilerna.Specify a location in which to save the project files.
Välj Slutför.Select Finish.
Skapa ett Firebase-projekt som har stöd för FCMCreate a Firebase project that supports FCM
Logga in på Firebase-konsolen.Sign in to the Firebase console. Skapa ett nytt Firebase-projekt om du inte redan har ett.Create a new Firebase project if you don't already have one.
När du har skapat ett projekt väljer du Lägg till Firebase till din Android-app.After you create your project, select Add Firebase to your Android app.
Utför följande steg på sidan Lägg till Firebase på din Android-app :On the Add Firebase to your Android app page, take the following steps:
För namn på Android-paket kopierar du värdet för din applicationId i programmets build. gradle-fil.For Android package name, copy the value of your applicationId in your application's build.gradle file. I det här exemplet är det
com.fabrikam.fcmtutorial1app
.In this example, it'scom.fabrikam.fcmtutorial1app
.Välj Registrera app.Select Register app.
Välj hämta google-services.jspå, spara filen i app -mappen i projektet och välj sedan Nästa.Select Download google-services.json, save the file into the app folder of your project, and then select Next.
Gör följande konfigurations ändringar i projektet i Android Studio.Make the following configuration changes to your project in Android Studio.
I filen build. gradle för projekt nivå ( < Project > /build.gradle) lägger du till följande-instruktion i avsnittet beroenden .In your project-level build.gradle file (<project>/build.gradle), add the following statement to the dependencies section.
classpath 'com.google.gms:google-services:4.0.1'
Lägg till följande-instruktioner i avsnittet beroenden i filen build. gradle för app-nivå ( < Project > / < app-module > /build.gradle). In your app-level build.gradle file (<project>/<app-module>/build.gradle), add the following statements to the dependencies section.
implementation 'com.google.firebase:firebase-core:16.0.8' implementation 'com.google.firebase:firebase-messaging:17.3.4'
Lägg till följande rad i slutet av filen build. gradle för app-nivå efter avsnittet beroenden.Add the following line to the end of the app-level build.gradle file after the dependencies section.
apply plugin: 'com.google.gms.google-services'
Välj Synkronisera nu i verktygsfältet.Select Sync now on the toolbar.
Välj Nästa.Select Next.
Välj hoppa över det här steget.Select Skip this step.
Välj kugghjulet för ditt projekt i Firebase-konsolen.In the Firebase console, select the cog for your project. Välj sedan Projektinställningar.Then select Project Settings.
Om du inte har hämtat google-services.jsfilen till mappen app i Android Studio-projektet kan du göra det på den här sidan.If you haven't downloaded the google-services.json file into the app folder of your Android Studio project, you can do so on this page.
Växla till fliken Cloud Messaging överst.Switch to the Cloud Messaging tab at the top.
Kopiera och spara Server nyckeln för senare användning.Copy and save the Server key for later use. Du använder det här värdet för att konfigurera hubben.You use this value to configure your hub.
Konfigurera en hubbConfigure a hub
Logga in på Azure-portalen.Sign in to the Azure portal.
Välj alla tjänster på den vänstra menyn och välj sedan Notification Hubs i avsnittet mobil .Select All services on the left menu, and then select Notification Hubs in the Mobile section. Välj stjärn ikonen bredvid tjänst namnet för att lägga till tjänsten i Favoriter -avsnittet på den vänstra menyn.Select the star icon next to the service name to add the service to the FAVORITES section on the left menu. När du har lagt till Notification Hubs i Favoriter väljer du den på den vänstra menyn.After you add Notification Hubs to FAVORITES, select it on the left menu.
På sidan Notification Hubs väljer du Lägg till i verktygsfältet.On the Notification Hubs page, select Add on the toolbar.
På sidan Notification Hub gör du följande:On the Notification Hub page, do the following steps:
Ange ett namn i Notification Hub.Enter a name in Notification Hub.
Ange ett namn i skapa ett nytt namn område.Enter a name in Create a new namespace. En namnrymd innehåller en eller flera hubbar.A namespace contains one or more hubs.
Välj ett värde i list rutan plats .Select a value from the Location drop-down list box. Det här värdet anger den plats där du vill skapa hubben.This value specifies the location in which you want to create the hub.
Välj en befintlig resurs grupp i resurs gruppen eller skapa ett namn för en ny resurs grupp.Select an existing resource group in Resource Group, or create a name for a new resource group.
Välj Skapa.Select Create.
Välj meddelanden (klock ikonen) och välj sedan gå till resurs.Select Notifications (the bell icon), and then select Go to resource. Du kan också uppdatera listan på sidan Notification Hubs och välja hubben.You can also refresh the list on the Notification Hubs page and select your hub.
Välj Åtkomstprinciper i listan.Select Access Policies from the list. Observera att de två anslutnings strängarna är tillgängliga för dig.Note that the two connection strings are available to you. Du behöver dem senare för att hantera push-meddelanden.You'll need them later to handle push notifications.
Viktigt
Använd inte DefaultFullSharedAccessSignature -principen i ditt program.Do not use the DefaultFullSharedAccessSignature policy in your application. Detta är endast avsett att användas i Server delen.This is meant to be used in your back end only.
Konfigurera Firebase Cloud Messaging-inställningar för hubbenConfigure Firebase Cloud Messaging settings for the hub
Välj Google (GCM/FCM) i den vänstra rutan under Inställningar .In the left pane, under Settings, select Google (GCM/FCM).
Ange Server nyckeln för det FCM-projekt som du sparade tidigare.Enter the server key for the FCM project that you saved earlier.
Välj Spara i verktygsfältet.On the toolbar, select Save.
Azure Portal visar ett meddelande i aviseringar om att navet har uppdaterats.The Azure portal displays a message in alerts that the hub has been successfully updated. Knappen Spara är inaktiverad.The Save button is disabled.
Navet har nu kon figurer ATS för att fungera med Firebase Cloud Messaging.Your hub is now configured to work with Firebase Cloud Messaging. Du har också de anslutnings strängar som krävs för att skicka meddelanden till en enhet och registrera en app för att ta emot meddelanden.You also have the connection strings that are necessary to send notifications to a device and register an app to receive notifications.
Anslut appen till meddelandehubbenConnect your app to the notification hub
Lägga till Google Play-tjänster till projektetAdd Google Play services to the project
I Android Studio väljer du verktyg på menyn och sedan SDK-hanteraren.In Android Studio, select Tools on the menu, and then select SDK Manager.
Välj mål versionen av Android SDK som används i projektet.Select the target version of the Android SDK that is used in your project. Välj sedan Visa paket information.Then select Show Package Details.
Välj Google API: er om det inte redan är installerat.Select Google APIs, if it's not already installed.
Växla till fliken SDK-verktyg . Om du inte redan har installerat Google Play-tjänster väljer du Google Play Services som visas i följande bild.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. Välj sedan Använd för att installera.Then select Apply to install. Anteckna SDK-sökvägen för användning i ett senare steg.Note the SDK path, for use in a later step.
Om du ser dialogrutan Bekräfta ändringen väljer du OK.If you see the Confirm Change dialog box, select OK. De begärda komponenterna installeras.The Component Installer installs the requested components. Välj Slutför när komponenterna har installerats.Select Finish after the components are installed.
Välj OK för att stänga dialogrutan Inställningar för nya projekt.Select OK to close the Settings for New Projects dialog box.
Öppna AndroidManifest.xml-filen och Lägg sedan till följande tagg i program tag gen.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" />
Lägg till Azure Notification Hubs-bibliotekAdd Azure Notification Hubs libraries
I filen build. Gradle för appen lägger du till följande rader i avsnittet beroenden.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'
Lägg till följande lagringsplats efter avsnittet beroenden.Add the following repository after the dependencies section.
repositories { maven { url "https://dl.bintray.com/microsoftazuremobile/SDK" } }
Lägg till stöd för Google FirebaseAdd Google Firebase support
I filen build. Gradle för appen lägger du till följande rader i avsnittet beroenden om de inte redan finns.In the Build.Gradle file for the app, add the following lines in the dependencies section if they don't already exist.
implementation 'com.google.firebase:firebase-core:16.0.8' implementation 'com.google.firebase:firebase-messaging:17.3.4'
Lägg till följande plugin-program i slutet av filen om det inte redan finns där.Add the following plug-in at the end of the file if it's not already there.
apply plugin: 'com.google.gms.google-services'
Välj Synkronisera nu i verktygsfältet.Select Sync Now on the toolbar.
Uppdatera AndroidManifest.xml-filenUpdate the AndroidManifest.xml file
När du har fått din FCM kan du använda den för att Registrera dig för Azure Notification Hubs.After you receive your FCM registration token, you use it to register with Azure Notification Hubs. Du har stöd för den här registreringen i bakgrunden genom att använda ett
IntentService
namnRegistrationIntentService
.You support this registration in the background by using anIntentService
namedRegistrationIntentService
. Den här tjänsten uppdaterar också din FCM-registrerings-token.This service also refreshes your FCM registration token. Du kan också skapa en klass med namnet som en underordnadFirebaseService
klassFirebaseMessagingService
och åsidosättaonMessageReceived
metoden för att ta emot och hantera meddelanden.You also create a class namedFirebaseService
as a subclass ofFirebaseMessagingService
and override theonMessageReceived
method to receive and handle notifications.Lägg till följande tjänstedefinition i filen AndroidManifest.xml inuti taggen
<application>
.Add the following service definition to the AndroidManifest.xml file, inside the<application>
tag.<service android:name=".RegistrationIntentService" android:exported="false"> </service> <service android:name=".FirebaseService" android:exported="false"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT" /> </intent-filter> </service>
Lägg till följande nödvändiga FCM-relaterade behörigheter under-
</application>
taggen.Add the following necessary FCM-related permissions below the</application>
tag.<uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.GET_ACCOUNTS"/> <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
Lägg till kodAdd code
I projektvyn expanderar du app > src > main > Java.In the Project View, expand app > src > main > java. Högerklicka på mappen paket under Java, Välj ny och välj sedan Java-klass.Right-click your package folder under java, select New, and then select Java Class. Ange NotificationSettings som namn och välj sedan OK.Enter NotificationSettings for the name, and then select OK.
Se till att uppdatera dessa tre platshållare i följande kod för klassen
NotificationSettings
:Make sure to update these three placeholders in the following code for theNotificationSettings
class:HubListenConnectionString: Anslutningssträngen DefaultListenAccessSignature för din hubb.HubListenConnectionString: The DefaultListenAccessSignature connection string for your hub. Du kan kopiera anslutnings strängen genom att klicka på åtkomst principer i hubben i Azure Portal.You can copy that connection string by clicking Access Policies in your hub in the Azure portal.
HubName: Använd namnet på navet som visas på sidan hubb i Azure Portal.HubName: Use the name of your hub that appears in the hub page in the Azure portal.
NotificationSettings
kod:NotificationSettings
code:public class NotificationSettings { public static String HubName = "<Your HubName>"; public static String HubListenConnectionString = "<Enter your DefaultListenSharedAccessSignature connection string>"; }
Viktigt
Ange namn och DefaultListenSharedAccessSignature för navet innan du fortsätter.Enter the name and the DefaultListenSharedAccessSignature of your hub before proceeding further.
Lägg till ytterligare en ny klass i projektet och ge den namnet
RegistrationIntentService
.Add another new class to your project namedRegistrationIntentService
. Den här klassen implementerarIntentService
gränssnittet.This class implements theIntentService
interface. Den hanterar också uppdateringen av FCM-token och registrering med Notification Hub.It also handles refreshing the FCM token and registering with the notification hub.Använd följande kod för den här klassen.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.tasks.OnSuccessListener; import com.google.firebase.iid.FirebaseInstanceId; import com.google.firebase.iid.InstanceIdResult; import com.microsoft.windowsazure.messaging.NotificationHub; import java.util.concurrent.TimeUnit; public class RegistrationIntentService extends IntentService { private static final String TAG = "RegIntentService"; String FCM_token = null; private NotificationHub hub; public RegistrationIntentService() { super(TAG); } @Override protected void onHandleIntent(Intent intent) { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); String resultString = null; String regID = null; String storedToken = null; try { FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(new OnSuccessListener<InstanceIdResult>() { @Override public void onSuccess(InstanceIdResult instanceIdResult) { FCM_token = instanceIdResult.getToken(); Log.d(TAG, "FCM Registration Token: " + FCM_token); } }); TimeUnit.SECONDS.sleep(1); // 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.d(TAG, "Attempting a new registration with NH using FCM token : " + FCM_token); regID = hub.register(FCM_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 = "New NH Registration Successfully - RegId : " + regID; Log.d(TAG, resultString); sharedPreferences.edit().putString("registrationID", regID ).apply(); sharedPreferences.edit().putString("FCMtoken", FCM_token ).apply(); } // Check to see if the token has been compromised and needs refreshing. else if (!(storedToken = sharedPreferences.getString("FCMtoken", "")).equals(FCM_token)) { NotificationHub hub = new NotificationHub(NotificationSettings.HubName, NotificationSettings.HubListenConnectionString, this); Log.d(TAG, "NH Registration refreshing with token : " + FCM_token); regID = hub.register(FCM_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 = "New NH Registration Successfully - RegId : " + regID; Log.d(TAG, resultString); sharedPreferences.edit().putString("registrationID", regID ).apply(); sharedPreferences.edit().putString("FCMtoken", FCM_token ).apply(); } else { resultString = "Previously Registered Successfully - RegId : " + regID; } } catch (Exception e) { Log.e(TAG, resultString="Failed to complete registration", e); // If an exception happens while fetching the new token or updating 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); } } }
I
MainActivity
-klassen lägger du till följandeimport
instruktioner ovanför klass deklarationen.In theMainActivity
class, add the followingimport
statements above the class declaration.import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GoogleApiAvailability; import android.content.Intent; import android.util.Log; import android.widget.TextView; import android.widget.Toast;
Lägg till följande medlemmar högst upp i klassen.Add the following members at the top of the class. Du använder de här fälten för att kontrollera tillgängligheten för Google Play-tjänster, enligt rekommendationer från Google.You use these fields to check the availability of Google Play Services as recommended by Google.
public static MainActivity mainActivity; public static Boolean isVisible = false; private static final String TAG = "MainActivity"; private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
I
MainActivity
-klassen lägger du till följande metod för att kontrol lera tillgängligheten för Google Play-tjänster.In theMainActivity
class, add the following method to check 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 box that enables 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; }
I
MainActivity
-klassen lägger du till följande kod som söker efter Google Play-tjänster innan du anropar förIntentService
att hämta din FCM för registrering och registrera dig för din hubb:In theMainActivity
class, add the following code that checks for Google Play Services before calling theIntentService
to get your FCM registration token and register with your hub:public void registerWithNotificationHubs() { if (checkPlayServices()) { // Start IntentService to register this application with FCM. Intent intent = new Intent(this, RegistrationIntentService.class); startService(intent); } }
I
OnCreate
-metoden förMainActivity
-klassen lägger du till följande kod för att starta registrerings processen när aktiviteten skapas:In theOnCreate
method of theMainActivity
class, add the following code to start the registration process when the activity is created:@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mainActivity = this; registerWithNotificationHubs(); FirebaseService.createChannelAndHandleNotifications(getApplicationContext()); }
Om du vill kontrol lera appens tillstånd och rapport status i appen lägger du till dessa ytterligare metoder för att
MainActivity
:To verify app state and report status in your app, add these additional methods toMainActivity
:@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); } }); }
I metoden
ToastNotify
används kontrollen ”Hello World”TextView
för att rapportera status och meddelanden på ett beständigt sätt i appen.TheToastNotify
method uses the "Hello World"TextView
control to report status and notifications persistently in the app. I layouten res > layout > activity_main.xml lägger du till följande ID för kontrollen.In your res > layout > activity_main.xml layout, add the following ID for that control.android:id="@+id/text_hello"
Härnäst lägger du till en underklass för mottagaren som du definierade i AndroidManifest.xml.Next you add a subclass for the receiver that you defined in AndroidManifest.xml. Lägg till ytterligare en ny klass i projektet och ge den namnet
FirebaseService
.Add another new class to your project namedFirebaseService
.Lägg till följande importuttryck längst upp i
FirebaseService.java
:Add the following import statements at the top ofFirebaseService.java
:import com.google.firebase.messaging.FirebaseMessagingService; import com.google.firebase.messaging.RemoteMessage; import android.util.Log; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.media.RingtoneManager; import android.net.Uri; import android.os.Build; import android.os.Bundle; import androidx.core.app.NotificationCompat;
Lägg till följande kod för
FirebaseService
-klassen, vilket gör den till en underordnad klassFirebaseMessagingService
.Add the following code for theFirebaseService
class, making it a subclass ofFirebaseMessagingService
.Den här koden åsidosätter
onMessageReceived
metod-och rapport meddelanden som tas emot.This code overrides theonMessageReceived
method and reports notifications that are received. den skickar även push-meddelandet till Android Notification Manager med hjälp av-sendNotification()
metoden.it also sends the push notification to the Android notification manager by using thesendNotification()
method. AnropasendNotification()
metoden när appen inte körs och ett meddelande tas emot.Call thesendNotification()
method when the app isn't running and a notification is received.public class FirebaseService extends FirebaseMessagingService { private String TAG = "FirebaseService"; public static final String NOTIFICATION_CHANNEL_ID = "nh-demo-channel-id"; public static final String NOTIFICATION_CHANNEL_NAME = "Notification Hubs Demo Channel"; public static final String NOTIFICATION_CHANNEL_DESCRIPTION = "Notification Hubs Demo Channel"; public static final int NOTIFICATION_ID = 1; private NotificationManager mNotificationManager; NotificationCompat.Builder builder; static Context ctx; @Override public void onMessageReceived(RemoteMessage remoteMessage) { // ... // TODO(developer): Handle FCM messages here. // Not getting messages here? See why this may be: https://goo.gl/39bRNJ Log.d(TAG, "From: " + remoteMessage.getFrom()); String nhMessage; // Check if message contains a notification payload. if (remoteMessage.getNotification() != null) { Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody()); nhMessage = remoteMessage.getNotification().getBody(); } else { nhMessage = remoteMessage.getData().values().iterator().next(); } // Also if you intend on generating your own notifications as a result of a received FCM // message, here is where that should be initiated. See sendNotification method below. if (MainActivity.isVisible) { MainActivity.mainActivity.ToastNotify(nhMessage); } sendNotification(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 notificationBuilder = new NotificationCompat.Builder( ctx, NOTIFICATION_CHANNEL_ID) .setContentText(msg) .setPriority(NotificationCompat.PRIORITY_HIGH) .setSmallIcon(android.R.drawable.ic_popup_reminder) .setBadgeIconType(NotificationCompat.BADGE_ICON_SMALL); notificationBuilder.setContentIntent(contentIntent); mNotificationManager.notify(NOTIFICATION_ID, notificationBuilder.build()); } public static void createChannelAndHandleNotifications(Context context) { ctx = context; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel channel = new NotificationChannel( NOTIFICATION_CHANNEL_ID, NOTIFICATION_CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH); channel.setDescription(NOTIFICATION_CHANNEL_DESCRIPTION); channel.setShowBadge(true); NotificationManager notificationManager = context.getSystemService(NotificationManager.class); notificationManager.createNotificationChannel(channel); } } }
I Android Studio väljer du skapa återskapa projekt på Meny raden > för att kontrol lera att det inte finns några fel i koden.In Android Studio, on the menu bar, select Build > Rebuild Project to make sure that there aren't any errors in your code. Om du får ett fel meddelande om
ic_launcher
ikonen tar du bort följande-instruktion från AndroidManifest.xml-filen:If you receive an error about theic_launcher
icon, remove the following statement from the AndroidManifest.xml file:android:icon="@mipmap/ic_launcher"
Se till att du har en virtuell enhet för att köra appen.Ensure you have a virtual device for running the app. Om du inte har ett kan du lägga till ett på följande sätt:If you do not have one, add one as follows:
Kör appen på den valda enheten och kontrol lera att den har registrerats med hubben.Run the app on your selected device and verify that it registers successfully with the hub.
Anteckning
Registreringen kan Miss inledas under den första starten tills
onTokenRefresh()
metoden för instans-ID-tjänst anropas.Registration might fail during the initial launch until theonTokenRefresh()
method of the instance ID service is called. Uppdateringen bör initiera en lyckad registrering hos meddelandehubben.The refresh should initiate a successful registration with the notification hub.
Testa att skicka ett meddelande från meddelandehubbenTest send notification from the notification hub
Du kan skicka push-meddelanden från [Azure portalen] genom att utföra följande steg:You can send push notifications from the Azure portal by taking the following steps:
På sidan för aviserings hubben på sidan Azure Portal väljer du testa skicka i fel söknings avsnittet.In the Azure portal, on the Notification Hub page for your hub, select Test Send in the Troubleshooting section.
Välj Android under Plattformar.For Platforms, select Android.
Välj Skicka.Select Send. Du kan inte se ett meddelande på Android-enheten ännu eftersom du inte har kört mobilappen på den.You won't see a notification on the Android device yet because you haven't run the mobile app on it. När du har kört mobilappen väljer du knappen Skicka igen för att se meddelandet.After you run the mobile app, select the Send button again to see the notification message.
Visa åtgärdens resultat i listan längst ned.See the result of the operation in the list at the bottom.
Du ser meddelandet på enheten.You see the notification message on your device.
Push-meddelanden skickas vanligtvis via en serverdelstjänst, till exempel Mobile Apps eller ASP.NET, med hjälp av ett kompatibelt bibliotek.Push notifications are normally sent in a back-end service like Mobile Apps or ASP.NET using a compatible library. Om ett bibliotek inte är tillgängligt för Server delen kan du också använda REST API direkt för att skicka meddelanden.If a library isn't available for your back end, you can also use the REST API directly to send notification messages.
Här är en lista över några andra själv studie kurser som du kanske vill granska för att skicka meddelanden:Here is a list of some other tutorials you might want to review for sending notifications:
- Azure-Mobile Apps: ett exempel på hur du skickar meddelanden från en Mobile Apps Server del som är integrerad med Notification Hubs finns i lägga till push-meddelanden till din 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: Använd Notification Hubs för push-meddelanden till användare.ASP.NET: Use Notification Hubs to push notifications to users.
- Azure Notification Hub Java SDK: Se Använda Notification Hubs från Java för information om att skicka meddelanden från Java.Azure Notification Hub Java SDK: See How to use Notification Hubs from Java for sending notifications from Java. Det här har testats i Eclipse för Android-utveckling.This has been tested in Eclipse for Android Development.
- PHP: Använda Notification Hubs från PHP.PHP: How to use Notification Hubs from PHP.
Kör mobilappen i emulatornRun the mobile app on emulator
Innan du testar push-meddelanden i en emulator ser du till att din emulator-avbildning stöder den Google API-nivå som du har valt för din app.Before you test push notifications inside an emulator, make sure that your emulator image supports the Google API level that you chose for your app. Om avbildningen inte har stöd för interna Google-API: er kan du få tjänsten _ inte _ tillgängligt som undantag.If your image doesn't support native Google APIs, you might get the SERVICE_NOT_AVAILABLE exception.
Kontrol lera också att du har lagt till ditt Google-konto till din aktiva emulator under Inställningar > konton.Also make sure that you've added your Google account to your running emulator under Settings > Accounts. Annars kan försök att registrera med FCM leda till att autentiseringen _ Miss lyckas undantag.Otherwise, your attempts to register with FCM might result in the AUTHENTICATION_FAILED exception.
Nästa stegNext steps
I den här självstudien använde du Firebase Cloud Messaging för att skicka meddelanden till alla Android-enheter som har registrerats med tjänsten.In this tutorial, you used Firebase Cloud Messaging to broadcast notifications to all Android devices that were registered with the service. Information om hur du skickar meddelanden till specifika enheter finns i följande självstudie:To learn how to push notifications to specific devices, advance to the following tutorial: