教學課程:使用 Firebase SDK 0.6 版將推播通知傳送至 Android 裝置

本教學課程說明如何使用 Azure 通知中樞和 Firebase 雲端傳訊 (FCM) SDK 0.6 版將推播通知傳送至 Android 應用程式。 在本教學課程中,您會建立空白的Android應用程式,以使用Firebase雲端通訊 (FCM) 接收推播通知。

Azure 通知中樞與 Firebase 雲端傳訊 (FCM) v1 整合的核心功能已準備好進行測試。 提醒您,Google 將於 2024 年 6 月 20 日停止支援 FCM 舊版 HTTP,因此您必須先將應用程式和通知承載移轉至新的格式,然後才行。 到 2024 年 3 月 1 日,所有上線方法都已準備好進行移轉。

為了協助進行這項轉換,我們邀請您加入我們的預覽計劃,並在 2024 年 2 月測試 REST API 的 FCM v1 上線程式。 預覽可讓您提早存取新功能,以及提供意見反應並回報任何問題的機會。

如果您有興趣加入預覽計劃, 請透過電子郵件 到 2024 年 1 月 25 日與我們連絡。 我們將回復如何使用 Azure 入口網站 或 REST API 上線至 FCM v1 的指示。 您也會收到我們的文件和支援通道的連結。

FCM v1 的概念

  • 支援新的平臺類型,稱為 FCM v1
  • 新的 API、認證、註冊和安裝將用於 FCM v1。

注意

本文中現有的 FCM 平台稱為 FCM 舊版

移轉步驟 (預覽)

Firebase 雲端傳訊 (FCM) 舊版 API 將於 2024 年 7 月淘汰。 您可以在 2024 年 3 月 1 日開始從舊版 HTTP 通訊協定移轉至 FCM v1。 您必須在 2024 年 6 月前完成移轉。

重要

目前不需要採取任何動作;您可以在這裡查看以取得進一步指示。

如果您有任何問題或問題,請連絡我們的支援小組。

若要從 FCM 舊版移轉至 FCM v1,以下是您預期的情況:

  1. 提供 FCM v1 的認證:您必須提供 FCM v1 認證來設定通知。
  2. 更新用戶端應用程式以開始註冊為 FCM v1 裝置:一旦您準備好開始支援 FCMv1 裝置,請更新用戶端應用程式,讓任何新裝置開始註冊為 FCM v1 ,而不是 FCM 舊版。 這可確保一旦 FCM 舊版已被取代,通知就會適當地傳送給使用者。
  3. 更新伺服器應用程式以將通知傳送至 FCM v1:完成先前的步驟之後,您就可以使用新的 API 開始傳送通知。
  4. 停止將通知傳送至 FCM 舊版:一旦所有現有的裝置註冊為 FCM v1 裝置,請停止將通知傳送至 FCM 舊版。 此時,您應該將所有通知獨佔傳送至 FCM v1,而且應該完全移轉。

您可以從 GitHub 下載本教學課程的完整程式碼。

在本教學課程中,您會採取下列步驟:

  • 建立 Android Studio 專案。
  • 建立支援 Firebase 雲端傳訊的 Firebase 專案。
  • 建立 中樞。
  • 連線 您的應用程式至中樞。
  • 測試應用程式。

必要條件

若要完成本教學課程,您必須擁有作用中的 Azure 帳戶。 如果您沒有帳戶,只要幾分鐘就能建立免費試用帳戶。 如需詳細資料,請參閱 Azure 免費試用

您也需要下列項目:

  • 最新版的 Android Studio
  • 適用於 Firebase 雲端傳訊的 Android 2.3 或更高版本
  • Firebase 雲端通訊的 Google 存放庫修訂 27 或更高版本
  • 適用於 Firebase 雲端通訊的 Google Play Services 9.0.2 或更高版本

完成本教學課程是執行Android應用程式所有其他通知中樞教學課程的必要條件。

建立 Android Studio 專案

  1. 啟動 Android Studio。
  2. 選取 [ 檔案],指向 [ 新增],然後選取 [ 新增專案]。
  3. 在 [ 選擇您的專案 ] 頁面上,選取 [空白活動],然後選取 [ 下一步]。
  4. 在 [ 設定專案 ] 頁面上,採取下列步驟:
    1. 輸入應用程式的名稱。

    2. 指定要在其中儲存項目檔的位置。

    3. 選取 [完成]。

      Configure your project)

建立支援 FCM 的 Firebase 專案

  1. 登入 Firebase 控制台。 如果您還沒有 Firebase 專案,請建立新的 Firebase 專案。

  2. 建立項目之後,請選取 [將 Firebase 新增至 Android 應用程式]。

    Add Firebase to your Android app

  3. 在 [ 將 Firebase 新增至 Android 應用程式] 頁面上,採取下列步驟:

    1. 針對Android套件名稱,請在應用程式的build.gradle檔案中複製applicationId的值。 在此範例中為 com.fabrikam.fcmtutorial1app

      Specify the package name

    2. 選取 [ 註冊應用程式]。

  4. 選取 [下載google-services.json],將檔案儲存到您專案的 app 資料夾中,然後選取 [下一步]。

    Download google-services.json

  5. 對 Android Studio 中的項目進行下列 設定變更

    1. 在您的專案層級 build.gradle 檔案中(<project>/build.gradle),將下列語句新增至 [相依性] 區段。

      classpath 'com.google.gms:google-services:4.0.1'
      
    2. 在您的應用層級 build.gradle 檔案中(project/app-module>/build.gradle),將下列語句新增至 [相依性] 區段。<><

      implementation 'com.google.firebase:firebase-core:16.0.8'
      implementation 'com.google.firebase:firebase-messaging:17.3.4'
      
    3. 在相依性區段之後,將下列這一行新增至應用層級 build.gradle 檔案的結尾。

      apply plugin: 'com.google.gms.google-services'
      
    4. 選取 工具列上的 [立即 同步]。

      build.gradle configuration changes

  6. 選取 [下一步]。

  7. 選取 [ 略過此步驟]。

    Skip the last step

  8. 在 Firebase 控制台中,選取項目的齒輪。 然後選取 [專案 設定]。

    Select Project Settings

  9. 如果您尚未將google-services.json檔案下載到 Android Studio 專案的應用程式 資料夾中,您可以在此頁面執行此動作。

  10. 切換至頂端的 [ 雲端傳訊 ] 索引標籤。

  11. 複製並儲存 伺服器金鑰 以供稍後使用。 您可以使用此值來設定中樞。

  12. 如果您在 Firebase Cloud Messaging 索引標籤上看不到 伺服器密鑰 ,請遵循下列其他步驟。

    1. 單擊 [雲端傳訊 API(舊版) 已停用] 🚫 標題的三點功能表
    2. 請遵循提供的連結來「在Google Cloud Console 中管理 API」。
    3. 在Google雲端控制台中,按按鈕以啟用googlecloudmessaging API。
    4. 請等待數分鐘。
    5. 返回 Firebase 控制台專案 Cloud Messaging 索引標籤,然後重新整理頁面。
    6. 查看雲端傳訊 API 標頭已變更為「已啟用雲端傳訊 API(舊版) ✅ 」,現在會顯示伺服器密鑰。

    Screenshot showing the Enable Cloud Messaging API (Legacy) tab.

設定中樞

  1. 登入 Azure 入口網站

  2. 選取 左側功能表上的 [所有服務 ]。 A screenshot showing select All Services for an existing namespace.

  3. 在 [篩選服務] 文本框中輸入通知中樞 選取服務名稱旁的星號圖示,將服務新增至左側功能表上的 [我的最愛] 區段。 選取 [ 通知中樞]。

    A screenshot showing how to filter for notification hubs.

  4. 在 [通知中 樞] 頁面上,選取 工具欄上的 [建立 ]。

    A screenshot showing how to create a new notification hub.

  5. 在 [通知中樞] 頁面上的 [基本] 索引標籤中,執行下列步驟:

    1. [訂用帳戶] 中,選取您想要使用的 Azure 訂用帳戶名稱,然後選取現有的資源群組,或建立新的資源群組。

    2. 在命名空間詳細數據中輸入新命名空間的唯一名稱。

    3. 命名空間包含一或多個通知中樞,因此請在通知中樞詳細數據中輸入中樞的名稱。

    4. 從 [ 位置 ] 下拉式清單框中選取值。 這個值會指定您要在其中建立中樞的位置。

      Screenshot showing notification hub details.

    5. 檢閱 [可用性區域] 選項。 如果您選擇具有可用性區域的區域,預設會選取複選框。 可用性區域 是付費功能,因此會將額外的費用新增至您的階層。

    6. 選擇災害復原選項:配對的復原區域彈性復原區域。 如果您選擇 [配對復原區域],則會顯示故障轉移區域。 如果您選取 [ 彈性復原區域],請使用下拉式清單從復原區域清單中選擇。

      Screenshot showing availability zone details.

    7. 選取 建立

  6. 部署完成時,請選取 [移至資源]。

設定中樞的 Firebase 雲端通訊設定

  1. 在左窗格中的 [設定] 下選取 [Google][GCM/FCM]。

  2. 輸入您稍早儲存之 FCM 專案的伺服器金鑰

  3. 在工具列上,選取 [ 儲存]。

    Azure Notification Hub - Google (FCM)

  4. Azure 入口網站 會在警示中顯示已成功更新中樞的訊息。 [ 儲存] 按鈕已停用。

您的中樞現在已設定為使用 Firebase 雲端通訊。 您也有將通知傳送至裝置並註冊應用程式以接收通知所需的 連接字串。

將您的應用程式 連線 至通知中樞

將Google Play服務新增至專案

  1. 在 Android Studio 中,選取 功能表上的 [工具 ],然後選取 [SDK 管理員]。

  2. 選取專案中所使用的 Android SDK 目標版本。 然後選取 [ 顯示套件詳細數據]。

    Android SDK Manager - select target version

  3. 如果尚未安裝,請選取 [Google API]。

    Android SDK Manager - Google APIs selected

  4. 切換至 [ SDK 工具] 索引 標籤。如果您尚未安裝Google Play服務,請選取 [Google Play 服務 ],如下圖所示。 然後選取 [ 套用 ] 進行安裝。 請記下 SDK 路徑,以供後續步驟使用。

    Android SDK Manager - Google Play Services selected

  5. 如果您看到 [ 確認變更 ] 對話框,請選取 [ 確定]。 元件安裝程式會安裝要求的元件。 安裝元件之後,選取 [ 完成 ]。

  6. 選取 [確定] 以關閉 [新增專案] 對話框的 [設定]。

  7. 開啟AndroidManifest.xml檔案,然後將下列標籤新增至 應用程式 標籤。

    <meta-data android:name="com.google.android.gms.version"
         android:value="@integer/google_play_services_version" />
    

新增 Azure 通知中樞連結庫

  1. 在應用程式的 Build.Gradle 檔案中,於 [相依性] 區段中新增下列幾行。

    implementation 'com.microsoft.azure:notification-hubs-android-sdk:0.6@aar'
    
  2. 在 [相依性] 區段之後新增下列存放庫。

    repositories {
        maven {
            url "https://dl.bintray.com/microsoftazuremobile/SDK"
        }
    }
    

新增Google Firebase支援

  1. 在應用程式的 Build.Gradle 檔案中,如果相依性區段中還不存在,請在 相依性 區段中新增下列幾行。

    implementation 'com.google.firebase:firebase-core:16.0.8'
    implementation 'com.google.firebase:firebase-messaging:17.3.4'
    implementation 'com.google.firebase:firebase-iid:21.1.0'
    
  2. 如果檔案尚未存在,請在檔案結尾新增下列外掛程式。

    apply plugin: 'com.google.gms.google-services'
    
  3. 選取工具列上的 [ 立即 同步處理]。

更新AndroidManifest.xml檔案

  1. 收到 FCM 註冊令牌之後,您可以使用它向 Azure 通知中樞註冊。 您可以使用具名 RegistrationIntentService的 ,在背景IntentService支援此註冊。 此服務也會重新整理您的 FCM 註冊令牌。 您也會建立名為 FirebaseService 的類別做為 的 FirebaseMessagingService 子類別,並覆寫 onMessageReceived 方法來接收和處理通知。

    將下列服務定義新增至 標籤內的 <application> AndroidManifest.xml檔案。

    <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>
    
  2. 在標籤下方 </application> 新增下列必要的 FCM 相關許可權。

    <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" />
    

新增程式碼

  1. 在 [項目檢視] 中,展開應用程式>src>主要>Java。 以滑鼠右鍵按兩下 java 下的套件資料夾,選取[新增],然後選取 [Java 類別]。 輸入 Notification 設定 以取得名稱,然後選取 [確定]。

    請務必在 類別的下列程式代碼 NotificationSettings 中更新這兩個佔位元元:

    • HubListen 連線 ionString中樞的 DefaultListenAccessSignature 連接字串。 您可以按下 Azure 入口網站 中樞的 [存取原則] 來複製該 連接字串

    • HubName:使用出現在 Azure 入口網站 中樞頁面中的中樞名稱。

      NotificationSettings 代碼:

      public class NotificationSettings {
          public static String HubName = "<Your HubName>";
          public static String HubListenConnectionString = "<Enter your DefaultListenSharedAccessSignature connection string>";
      }
      

      重要

      輸入 中樞的名稱DefaultListenSharedAccessSignature ,再繼續進行。

  2. 將另一個新類別新增至名為 RegistrationIntentService的專案。 這個類別會實作 IntentService 介面。 它也會處理 重新整理 FCM 令牌 ,並 向通知中樞註冊。

    針對這個類別使用下列程序代碼。

    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);
            }
        }
    }
    
  3. 在類別中 MainActivity ,在類別宣告上方新增下列 import 語句。

    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;
    
  4. 在類別頂端新增下列成員。 您可以使用這些欄位來 檢查 Google Play 服務的可用性,如 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;
    
  5. 在類別中 MainActivity ,新增下列方法來檢查Google Play服務的可用性。

    /**
    * 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;
    }
    
  6. 在 類別中 MainActivity ,新增下列程序代碼,在呼叫 IntentService 以取得 FCM 註冊令牌並向中樞註冊之前,先檢查 Google Play 服務:

    public void registerWithNotificationHubs()
    {
        if (checkPlayServices()) {
            // Start IntentService to register this application with FCM.
            Intent intent = new Intent(this, RegistrationIntentService.class);
            startService(intent);
        }
    }
    
  7. OnCreate 類別的 方法中 MainActivity ,新增下列程序代碼,以在建立活動時啟動註冊程式:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        mainActivity = this;
        registerWithNotificationHubs();
        FirebaseService.createChannelAndHandleNotifications(getApplicationContext());
    }
    
  8. 若要確認應用程式中的應用程式狀態和報告狀態,請將下列其他方法新增至 MainActivity

    @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);
            }
        });
    }
    
  9. 方法 ToastNotify使用 「Hello World」TextView 控制程式,在應用程式中持續報告狀態和通知。 在 res> 配置activity_main.xml>面配置中,新增該控件的下列標識碼。

    android:id="@+id/text_hello"
    

    Screenshot that shows the android:id=

  10. 接下來,您會為在 AndroidManifest.xml 中定義的接收者新增子類別。 將另一個新類別新增至名為 FirebaseService的專案。

  11. 在 頂端 FirebaseService.java新增下列 import 語句:

    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;
    
  12. 為類別新增下列程序代碼 FirebaseService ,使其成為的 FirebaseMessagingService子類別。

    此程式代碼會 onMessageReceived 覆寫收到的方法和報告通知。 它也會使用 sendNotification() 方法,將推播通知傳送至 Android 通知管理員。 sendNotification()當應用程式未執行且收到通知時,請呼叫 方法。

    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);
             }
        }
    }
    
  13. 在 Android Studio 的功能表列上,選取 [建>置重建專案] 以確定程式代碼中沒有任何錯誤。 如果您收到有關圖示的錯誤 ic_launcher ,請從 AndroidManifest.xml 檔案中移除下列語句:

        android:icon="@mipmap/ic_launcher"
    
  14. 請確定您有執行應用程式的虛擬設備。 如果您沒有帳戶,請新增一個,如下所示:

    1. Open device manager
    2. Create virtual device
  15. 在選取的裝置上執行應用程式,並確認它已成功向中樞註冊。

    注意

    在初始啟動期間,註冊可能會失敗,直到 onTokenRefresh() 呼叫實例標識符服務的方法為止。 重新整理應該會起始通知中樞的成功註冊。

    Device registration successful

測試從通知中樞傳送通知

您可以採取下列步驟,從 Azure 入口網站 傳送推播通知:

  1. 在 [Azure 入口網站] 中,於中樞的 [通知中樞] 頁面上,選取 [疑難解答] 區段中的 [測試傳送]。

  2. 針對 [ 平臺],選取 [Android]。

  3. 請選取傳送。 您尚未在 Android 裝置上看到通知,因為您尚未在裝置上執行行動應用程式。 執行行動應用程式之後,請再次選取 [ 傳送 ] 按鈕以查看通知訊息。

  4. 請參閱底部清單中作業的結果。

    Azure Notification Hubs - Test Send

  5. 您會在裝置上看到通知訊息。

    Notification message on device

推播通知通常會在後端服務中傳送,例如Mobile Apps或使用相容的連結庫 ASP.NET。 如果後端無法使用連結庫,您也可以直接使用 REST API 來傳送通知訊息。

以下是您可能想要檢閱以傳送通知的其他一些教學課程清單:

在模擬器上執行行動應用程式

在模擬器內測試推播通知之前,請確定模擬器映像支援您為應用程式選擇的Google API層級。 如果您的映像不支援原生 Google API,您可能會收到 SERVICE_NOT_AVAILABLE 例外狀況。

此外,請確定您已在 設定> Accounts 下,將 Google 帳戶新增至執行中的模擬器。 否則,嘗試向 FCM 註冊可能會導致 AUTHENTICATION_FAILED 例外狀況。

下一步

在本教學課程中,您已使用 Firebase 雲端通訊,將通知廣播至已向服務註冊的所有 Android 裝置。 若要瞭解如何將通知推送至特定裝置,請繼續進行下列教學課程: