다음을 통해 공유


푸시 알림 사용

푸시 알림을 통해 모바일 앱이 포그라운드로 실행되고 있지 않은 상황에서 채팅 스레드에서 발생하는 들어오는 메시지와 기타 작업에 대한 알림을 클라이언트에 알릴 수 있습니다. 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 project, Register your app with Firebase, Add a Firebase configuration file, Add 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 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.xml에서 WorkManager에 대한 기본 이니셜라이저를 사용하지 않도록 설정합니다.
    <!-- 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();
        }
    }

위의 코드에 대한 설명: 9단계에서 WorkManager의 기본 이니셜라이저를 사용하지 않도록 설정했습니다. 이 단계에서는 런타임 중에 WorkerManager를 만드는 사용자 지정 'WorkFactory'를 제공하는 Configuration.Provider를 구현합니다.

앱이 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"
>