푸시 알림을 사용하면 모바일 앱이 포그라운드에서 실행되고 있지 않을 때 들어오는 메시지 및 채팅 스레드에서 발생하는 기타 작업에 대한 알림을 클라이언트에 알 수 있습니다. Azure Communication Services는 구독할 수 있는 이벤트 목록을 지원합니다.
비고
채팅 푸시 알림은 1.1.0-beta.4 및 1.1.0부터 시작하는 버전에서 Android SDK에 대해 지원됩니다. 이전 버전에 등록 갱신과 관련된 알려진 문제가 있으므로 버전 2.0.0 이상 버전을 사용하는 것이 좋습니다. 8~12단계는 2.0.0보다 크거나 같은 버전에만 필요합니다.
ChatQuickstart 프로젝트에 대한 Firebase Cloud Messaging을 설정합니다.
Create a Firebase project,Register your app with Firebase,Add a Firebase configuration file,Add Firebase SDKs to your app및Edit your app manifest단계를 Firebase 설명서에서 완료하세요.Communication Services 리소스와 동일한 구독 내에서 알림 허브를 만들고, 허브에 대한 Firebase Cloud Messaging 설정을 구성하고, Notification Hub를 Communication Services 리소스에 연결합니다. 알림 허브 프로비저닝을 참조하세요.
동일한 디렉터리
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); } }파일
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;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); } }); } }); }함수
onCreate를MainActivity에서 업데이트합니다.@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); LocalBroadcastManager .getInstance(this) .registerReceiver( firebaseMessagingReceiver, new IntentFilter("<your_intent_name>")); }주석
<RECEIVE CHAT MESSAGES>다음에 다음 코드를 넣습니다.MainActivity
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
});
-
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">
-
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 -->
-
WorkManager종속성을build.gradle파일에 추가합니다.
def work_version = "2.7.1"
implementation "androidx.work:work-runtime:$work_version"
- 다음을 구현하는 클래스를 만들어 사용자 지정
WorkManager이니셜라이저를 추가합니다.Configuration.Provider
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단계에서 사용할 수 없습니다. 이 단계에서는 Configuration.Provider을(를) 구현하여 WorkFactory 사용자 지정을 제공하며, 이는 런타임 중에 WorkerManager을(를) 생성하는 책임을 가지고 있습니다.
앱이 Azure Function과 통합된 경우 메서드 onCreate()에서 애플리케이션 매개 변수를 초기화합니다. 메서드 getWorkManagerConfiguration() 는 애플리케이션이 시작될 때 작업, 서비스 또는 수신기 개체(콘텐츠 공급자 제외)를 만들기 전에 호출되므로 사용하기 전에 애플리케이션 매개 변수를 초기화할 수 있습니다. 자세한 내용은 샘플 채팅 앱을 참조하세요.
-
android:name=.MyAppConfiguration필드를 추가합니다. 이 필드는 11단계에서 사용한 클래스 이름을 사용하여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"
>