次の方法で共有


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

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

チャット プッシュ通知は、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 設定を構成し、Notification Hub を Communication Services リソースにリンクします。 Notification Hub のプロビジョニングを参照してください。

  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. ファイル MainActivity.javaの先頭に、次の import ステートメントを追加します。

       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. AndroidManifest.xml ファイルに xmlns:tools フィールドを追加します。
    <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. build.gradle ファイルにWorkManagerの依存関係を追加します。
    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 で無効になっています。 この手順では、カスタマイズされたWorkFactoryを提供するConfiguration.Providerを実装します。これは、実行時にWorkerManagerを作成する役割を担います。

アプリが Azure Function と統合されている場合は、メソッド 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"
>