プッシュ通知を有効にする

プッシュ通知は、モバイル アプリがフォアグラウンドで動作していない状況で、チャット スレッドで発生したメッセージの着信やその他の操作をクライアントに通知することができます。 Azure Communication Services は、サブスクライブ可能な一連のイベントをサポートしています。

Note

チャット プッシュ通知は、1.1.0-beta.4 および 1.1.0 以降のバージョンの Android SDK でサポートされています。 古いバージョンでは登録の更新に既知の問題があるため、バージョン 2.0.0 以降を使用することをお勧めします。 8 から 12 の手順は、2.0.0 以上のバージョンでのみ必要です。

  1. ChatQuickstart プロジェクトの Firebase Cloud Messaging を設定します。 Firebase ドキュメントの手順Create a Firebase projectRegister your app with FirebaseAdd a Firebase configuration fileAdd Firebase SDKs to your appEdit your app manifestを完了します。

  2. Communication Services リソースと同じサブスクリプション内に Notification Hub を作成し、Firebase Cloud Messaging の設定を Hub 用に行い、Notification Hub を Communication Services リソースにリンクします。 通知ハブのプロビジョニングを参照してください。

  3. MainActivity.java が存在するのと同じディレクトリに MyFirebaseMessagingService.java という新しいファイルを作成します。 MyFirebaseMessagingService.java に以下のコードをコピーします。 <your_package_name> は、MainActivity.java で使用されるパッケージ名に置き換える必要があります。 <your_intent_name> には独自の値を使用できます。 この値は、以下の手順 6 で使用します。

       package <your_package_name>;
    
       import android.content.Intent;
       import android.util.Log;
    
       import androidx.localbroadcastmanager.content.LocalBroadcastManager;
    
       import com.azure.android.communication.chat.models.ChatPushNotification;
       import com.google.firebase.messaging.FirebaseMessagingService;
       import com.google.firebase.messaging.RemoteMessage;
    
       import java.util.concurrent.Semaphore;
    
       public class MyFirebaseMessagingService extends FirebaseMessagingService {
           private static final String TAG = "MyFirebaseMsgService";
           public static Semaphore initCompleted = new Semaphore(1);
    
           @Override
           public void onMessageReceived(RemoteMessage remoteMessage) {
               try {
                   Log.d(TAG, "Incoming push notification.");
    
                   initCompleted.acquire();
    
                   if (remoteMessage.getData().size() > 0) {
                       ChatPushNotification chatPushNotification =
                           new ChatPushNotification().setPayload(remoteMessage.getData());
                       sendPushNotificationToActivity(chatPushNotification);
                   }
    
                   initCompleted.release();
               } catch (InterruptedException e) {
                   Log.e(TAG, "Error receiving push notification.");
               }
           }
    
           private void sendPushNotificationToActivity(ChatPushNotification chatPushNotification) {
               Log.d(TAG, "Passing push notification to Activity: " + chatPushNotification.getPayload());
               Intent intent = new Intent("<your_intent_name>");
               intent.putExtra("PushNotificationPayload", chatPushNotification);
               LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
           }
       }
    
    
  4. 次の import ステートメントをファイル MainActivity.java の先頭に追加します。

       import android.content.BroadcastReceiver;
       import android.content.Context;
       import android.content.Intent;
       import android.content.IntentFilter;
    
       import androidx.localbroadcastmanager.content.LocalBroadcastManager;
       import com.azure.android.communication.chat.models.ChatPushNotification;
       import com.google.android.gms.tasks.OnCompleteListener;
       import com.google.android.gms.tasks.Task;
       import com.google.firebase.messaging.FirebaseMessaging;
    
  5. 以下のコードを MainActivity クラスに追加します。

       private BroadcastReceiver firebaseMessagingReceiver = new BroadcastReceiver() {
           @Override
           public void onReceive(Context context, Intent intent) {
               ChatPushNotification pushNotification =
                   (ChatPushNotification) intent.getParcelableExtra("PushNotificationPayload");
    
               Log.d(TAG, "Push Notification received in MainActivity: " + pushNotification.getPayload());
    
               boolean isHandled = chatAsyncClient.handlePushNotification(pushNotification);
               if (!isHandled) {
                   Log.d(TAG, "No listener registered for incoming push notification!");
               }
           }
       };
    
    
       private void startFcmPushNotification() {
           FirebaseMessaging.getInstance().getToken()
               .addOnCompleteListener(new OnCompleteListener<String>() {
                   @Override
                   public void onComplete(@NonNull Task<String> task) {
                       if (!task.isSuccessful()) {
                           Log.w(TAG, "Fetching FCM registration token failed", task.getException());
                           return;
                       }
    
                       // Get new FCM registration token
                       String token = task.getResult();
    
                       // Log and toast
                       Log.d(TAG, "Fcm push token generated:" + token);
                       Toast.makeText(MainActivity.this, token, Toast.LENGTH_SHORT).show();
    
                       chatAsyncClient.startPushNotifications(token, new Consumer<Throwable>() {
                           @Override
                           public void accept(Throwable throwable) {
                               Log.w(TAG, "Registration failed for push notifications!", throwable);
                           }
                       });
                   }
               });
       }
    
    
  6. MainActivity で関数 onCreate を更新します。

       @Override
       protected void onCreate(Bundle savedInstanceState) {
           super.onCreate(savedInstanceState);
           setContentView(R.layout.activity_main);
    
           LocalBroadcastManager
               .getInstance(this)
               .registerReceiver(
                   firebaseMessagingReceiver,
                   new IntentFilter("<your_intent_name>"));
       }
    
  7. 次のコードを MainActivity のコメント <RECEIVE CHAT MESSAGES> の下に置きます。

   startFcmPushNotification();

   chatAsyncClient.addPushNotificationHandler(CHAT_MESSAGE_RECEIVED, (ChatEvent payload) -> {
       Log.i(TAG, "Push Notification CHAT_MESSAGE_RECEIVED.");
       ChatMessageReceivedEvent event = (ChatMessageReceivedEvent) payload;
       // You code to handle ChatMessageReceived event
   });
  1. xmlns:tools フィールドを AndroidManifest.xml ファイルに追加します。
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.azure.android.communication.chat.sampleapp">
  1. AndroidManifest.xmlWorkManager の既定の初期化子を無効にします。
    <!-- Disable the default initializer of WorkManager so that we could override it in MyAppConfiguration  -->
    <provider
        android:name="androidx.startup.InitializationProvider"
        android:authorities="${applicationId}.androidx-startup"
        android:exported="false"
        tools:node="merge">
      <!-- If you are using androidx.startup to initialize other components -->
      <meta-data
          android:name="androidx.work.WorkManagerInitializer"
          android:value="androidx.startup"
          tools:node="remove" />
    </provider>
    <!-- End of Disabling default initializer of WorkManager -->
  1. WorkManager 依存関係を build.gradle ファイルに追加します。
    def work_version = "2.7.1"
    implementation "androidx.work:work-runtime:$work_version"
  1. Configuration.Provider を実装するクラスを作成して、カスタム WorkManager 初期化子を追加します。
    public class MyAppConfiguration extends Application implements Configuration.Provider {
        Consumer<Throwable> exceptionHandler = new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) {
                Log.i("YOUR_TAG", "Registration failed for push notifications!" + throwable.getMessage());
            }
        };
    
        @Override
        public void onCreate() {
            super.onCreate();
            // Initialize application parameters here
            WorkManager.initialize(getApplicationContext(), getWorkManagerConfiguration());
        }
    
        @NonNull
        @Override
        public Configuration getWorkManagerConfiguration() {
            return new Configuration.Builder().
                setWorkerFactory(new RegistrationRenewalWorkerFactory(COMMUNICATION_TOKEN_CREDENTIAL, exceptionHandler)).build();
        }
    }

上記のコードの説明:WorkManager の既定の初期化子は、ステップ 9 で無効にされています。 このステップでは、実行時に WorkerManager を作成するカスタマイズされた "WorkFactory" を提供するための Configuration.Provider を実装します。

アプリが Azure 関数と統合されている場合、アプリケーション パラメーターの初期化を "onCreate()" メソッドに追加する必要があります。 "getWorkManagerConfiguration()" メソッドは、アプリケーションの開始時に、アクティビティ、サービス、またはレシーバー オブジェクト (コンテンツ プロバイダーを除く) が作成される前に呼び出され、それによってアプリケーション パラメーターを使われる前に初期化できます。 詳しくは、サンプル チャット アプリをご覧ください。

  1. 手順 11 のクラス名を使用する android:name=.MyAppConfiguration フィールドを AndroidManifest.xml に追加します。
<application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:theme="@style/Theme.AppCompat"
      android:supportsRtl="true"
      android:name=".MyAppConfiguration"
>