將推播通知新增至 Android 應用程式

概觀

在本教學課程中,您會將推播通知新增至 Android 快速入門專案,以便在每次插入一筆記錄時傳送推播通知至裝置。

如果您不要使用下載的快速入門伺服器專案,則需要推播通知擴充套件。 如需詳細資訊,請參閱使用 Azure Mobile Apps 的 .NET 後端伺服器 SDK

必要條件

您需要下列項目:

  • 根據您的專案後端的 IDE:

  • Android 2.3 或更新版本、Google Repository 版本 27 或更新版本,以及 Firebase 雲端傳訊適用的 Google Play 服務 9.0.2 或更新版本。

  • 完成 Android 快速入門

建立支援 Firebase 雲端通訊的專案

  1. 登入 Firebase 主控台。 建立新的 Firebase 專案 (如果您還沒有 Firebase 專案的話)。

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

    將 Firebase 新增至 Android 應用程式

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

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

      指定套件名稱

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

  4. 選取 [下載 google-services.json],將檔案儲存到專案的應用程式資料夾,然後選取 [下一步]

    下載 google-services.json

  5. 在 Android Studio 中對於專案進行下列設定變更

    1. 在專案層級 build.gradle檔案 (<專案>/build.gradle) 中,將下列陳述式加入到相依性區段。

      classpath 'com.google.gms:google-services:4.0.1'
      
    2. 在應用程式層級 build.gradle 檔案 (<project>/<app-module>/build.gradle) 中,將下列陳述式新增至 dependencies 區段。

      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 組態變更

  6. 選取 [下一步] 。

  7. 選取 [略過此步驟]

    略過最後一個步驟

  8. 在 Firebase 主控台中,選取您專案的齒輪圖示。 然後選取 [專案設定]。

    選取專案設定

  9. 如果您尚未將 google-services.json 檔案下載到 Android Studio 專案的 app 資料夾,可以在此頁面下載。

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

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

設定通知中樞

Azure App Service 的 Mobile Apps 使用 Azure 通知中樞來傳送推送,因此您將為行動應用程式設定通知中樞。

  1. Azure 入口網站中,移至 [應用程式服務],然後選取應用程式後端。 在 [設定] 底下,選取 [推播]

  2. 將通知中樞資源新增至應用程式,選取 [連線]。 您可以建立中樞或連線到現有的中樞。

    設定中樞

現在您已將通知中樞連接到 Mobile Apps 後端專案。 稍後您要設定此通知中樞,使其連線到平台通知系統 (PNS) 以推播至裝置。

設定 Azure 來傳送推播通知

  1. Azure 入口網站中,按一下 [瀏覽全部]>[應用程式服務],再按一下 [Mobile Apps 後端]。 在 [設定] 中,按一下 [App Service 推播],然後按一下通知中樞名稱。

  2. 移至 Google (GCM),輸入在先前程序中透過 Firebase 取得的伺服器金鑰值,然後按一下 [儲存]

    在入口網站中設定 API 金鑰

Mobile Apps 後端現已設定成使用 Firebase 雲端通訊。 這個設定可讓您透過通知中樞,將推播通知傳送到在 Android 裝置上執行的應用程式。

啟用伺服器專案的推播通知

使用符合後端專案類型的程式— .NET 後端Node.js後端

.NET 後端專案

  1. In Visual Studio, right-click the server project, and click Manage NuGet Packages. 搜尋 Microsoft.Azure.NotificationHubs,然後按一下 [安裝]。 這會安裝通知中樞用戶端程式庫。

  2. 在 Controllers 資料夾中,開啟 TodoItemController.cs 並新增下列 using 陳述式:

    using Microsoft.Azure.Mobile.Server.Config;
    using Microsoft.Azure.NotificationHubs;
    
  3. 以下列程式碼取代 PostTodoItem 方法:

    public async Task<IHttpActionResult> PostTodoItem(TodoItem item)
    {
        TodoItem current = await InsertAsync(item);
        // Get the settings for the server project.
        HttpConfiguration config = this.Configuration;
    
        MobileAppSettingsDictionary settings =
            this.Configuration.GetMobileAppSettingsProvider().GetMobileAppSettings();
    
        // Get the Notification Hubs credentials for the Mobile App.
        string notificationHubName = settings.NotificationHubName;
        string notificationHubConnection = settings
            .Connections[MobileAppSettingsKeys.NotificationHubConnectionString].ConnectionString;
    
        // Create a new Notification Hub client.
        NotificationHubClient hub = NotificationHubClient
        .CreateClientFromConnectionString(notificationHubConnection, notificationHubName);
    
        // Android payload
        var androidNotificationPayload = "{ \"data\" : {\"message\":\"" + item.Text + "\"}}";
    
        try
        {
            // Send the push notification and log the results.
            var result = await hub.SendGcmNativeNotificationAsync(androidNotificationPayload);
    
            // Write the success result to the logs.
            config.Services.GetTraceWriter().Info(result.State.ToString());
        }
        catch (System.Exception ex)
        {
            // Write the failure result to the logs.
            config.Services.GetTraceWriter()
                .Error(ex.Message, null, "Push.SendAsync Error");
        }
        return CreatedAtRoute("Tables", new { id = current.Id }, current);
    }
    
  4. 發佈伺服器專案。

Node.js後端專案

  1. 設定後端專案。

  2. 在 todoitem.js 檔案中,以下列程式碼取代現有的程式碼:

    var azureMobileApps = require('azure-mobile-apps'),
    promises = require('azure-mobile-apps/src/utilities/promises'),
    logger = require('azure-mobile-apps/src/logger');
    
    var table = azureMobileApps.table();
    
    table.insert(function (context) {
    // For more information about the Notification Hubs JavaScript SDK,
    // see https://aka.ms/nodejshubs
    logger.info('Running TodoItem.insert');
    
    // Define the GCM payload.
    var payload = {
        "data": {
            "message": context.item.text
        }
    };
    
    // Execute the insert.  The insert returns the results as a Promise,
    // Do the push as a post-execute action within the promise flow.
    return context.execute()
        .then(function (results) {
            // Only do the push if configured
            if (context.push) {
                // Send a GCM native notification.
                context.push.gcm.send(null, payload, function (error) {
                    if (error) {
                        logger.error('Error while sending push notification: ', error);
                    } else {
                        logger.info('Push notification sent successfully!');
                    }
                });
            }
            // Don't forget to return the results from the context.execute()
            return results;
        })
        .catch(function (error) {
            logger.error('Error while running context.execute: ', error);
        });
    });
    
    module.exports = table;
    

    插入新的 todo 項目時,這會傳送包含 item.text 的 GCM 通知。

  3. 在本機電腦中編輯檔案時,重新發布伺服器專案。

將推播通知新增至應用程式

本節中,您必須更新用戶端 Android 應用程式,以處理推播通知。

驗證 Android SDK 版本

由於持續進行開發,因此 Android Studio 中安裝的 Android SDK 版本可能與程式碼中的版本不相符。 此教學課程參照的 Android SDK 為 26 版,是撰寫本文時的最新版本。 隨著新修訂版 SDK 發行,版本號碼可能會隨之增加,我們建議您使用最新的可用版本。

版本不符合的兩個徵兆為:

  • 建置或重新建置專案時,您可能會收到 Gradle sync failed: Failed to find target with hash string 'android-XX' 之類的 Gradle 錯誤訊息。
  • 錯誤訊息可能是程式碼中必須根據 import 陳述式解析的標準 Android 物件所產生。

若出現其中任一項,則 Android Studio 中安裝的 Android SDK 版本可能與下載專案的 SDK 目標不相符。 若要確認版本,請進行下列變更:

  1. 在 Android Studio 中,按一下[工具>] [Android>SDK 管理員]。 若尚未安裝最新版的 SDK 平台,則按一下以安裝它。 記下版本號碼。

  2. 在 [專案總管] 索引標籤的 [Gradle 指令碼] 下,開啟檔案 build.gradle (Module: app)。 確定 compileSdkVersiontargetSdkVersion 已設為最新安裝的 SDK 版本。 build.gradle 外觀如下:

    android {
        compileSdkVersion 26
        defaultConfig {
            targetSdkVersion 26
        }
    }
    

下一個步驟是安裝 Google Play 服務。 Firebase 雲端通訊在開發和測試方面有一些 API 層級的最低需求,這些是資訊清單中的 minSdkVersion 屬性所必須遵守的。

如果您要以較舊的裝置進行測試,請參考將 Firebase 新增至 Android 專案,以判斷此值可以設定的下限值,然後加以適當設定。

將 Firebase 雲端通訊新增至專案

  1. 將 Firebase 新增至 Android 專案

  2. 在 Android Studio 中,選擇 [檔案>專案結構]。 依序選取 [通知]、[Firebase 雲端通訊],然後按一下 [確定]

新增程式碼

  1. 在您的 app 專案中開啟 AndroidManifest.xml 檔案。 在 application 起始標籤後新增下列程式碼:

    <service android:name=".ToDoMessagingService">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT"/>
        </intent-filter>
    </service>
    <service android:name=".ToDoInstanceIdService">
        <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
        </intent-filter>
    </service>
    
  2. 開啟檔案 ToDoActivity.java 並進行下列變更:

    • 新增匯入陳述式:

      import com.google.firebase.iid.FirebaseInstanceId;
      
    • MobileServiceClient 的定義從 [私人] 變更為 [公用靜態],如下所示:

      private static MobileServiceClient mClient;
      
    • 新增 registerPush 方法:

      public static void registerPush() {
          final String token = FirebaseInstanceId.getInstance().getToken();
          if (token != null) {
              new AsyncTask<Void, Void, Void>() {
                  protected Void doInBackground(Void... params) {
                      mClient.getPush().register(token);
                      return null;
                  }
              }.execute();
          }
      }
      
    • 更新 ToDoActivity 類別的 onCreate 方法。 確定在 MobileServiceClient 具現化之後新增此程式碼。

      registerPush();
      
  3. 新增類別來處理通知。 在 [專案總管] 中,開啟應用程式>java>your-project-namespace節點,然後以滑鼠右鍵按一下套件名稱節點。 按一下 [新增],然後按一下 [Java 類別]。 在 [名稱] 中,輸入 ToDoMessagingService,然後按一下 [確定]。 然後,將類別宣告取代為:

    import android.app.Notification;
    import android.app.NotificationManager;
    import android.app.PendingIntent;
    import android.content.Context;
    import android.content.Intent;
    
    import com.google.firebase.messaging.FirebaseMessagingService;
    import com.google.firebase.messaging.RemoteMessage;
    
    public class ToDoMessagingService extends FirebaseMessagingService {
    
        private static final int NOTIFICATION_ID = 1;
    
        @Override
        public void onMessageReceived(RemoteMessage remoteMessage) {
            String message = remoteMessage.getData().get("message");
            if (message != null) {
                sendNotification("Notification Hub Demo", message);
            }
        }
    
        private void sendNotification(String title, String messageBody) {
            PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, ToDoActivity.class), 0);
            Notification.Builder notificationBuilder = new Notification.Builder(this)
                    .setSmallIcon(R.drawable.ic_launcher)
                    .setContentTitle(title)
                    .setContentText(messageBody)
                    .setContentIntent(contentIntent);
            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            if (notificationManager != null) {
                notificationManager.notify(NOTIFICATION_ID, notificationBuilder.build());
            }
        }
    }
    
  4. 新增另一個類別來處理權杖的更新。 建立 ToDoInstanceIdService java 類別,並將類別宣告取代為:

    import com.google.firebase.iid.FirebaseInstanceIdService;
    
    public class ToDoInstanceIdService extends FirebaseInstanceIdService {
    
        @Override
        public void onTokenRefresh() {
            ToDoActivity.registerPush();
        }
    }
    

您的應用程式現在已更新為支援推播通知。

對已發佈的行動服務進行應用程式測試

您可以使用 USB 纜線直接連接 Android 手機,或使用模擬器中的虛擬裝置,對應用程式進行測試。

後續步驟

現在您已經完成了這個教學課程,可以考慮繼續進行下列其中一個教學課程: