啟用推播通知
推播通知可讓用戶端在行動應用程式未在前景執行的情況下,收到在聊天對話中傳入訊息和發生其他作業的通知。 Azure 通訊服務支援您可以訂閱的事件清單。
注意
從 1.1.0-beta.4 和 1.1.0 版本開始,Android SDK 支援聊天推播通知。 建議您使用 2.0.0 版或更新版本,因為舊版有註冊續約的已知問題。 只有等於或大於 2.0.0 的版本才需要 8 到 12 的步驟。
設定 ChatQuickstart 專案的 Firebase 雲端通訊。 完成 Firebase 文件中的步驟
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 雲端通訊設定,並將通知中樞連結至您的通訊服務資源。 請參閱 通知中樞佈建。
在
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 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); } }); } }); }
在
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>")); }
在
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
});
- 將 [
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">
- 在
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"
- 藉由建立實作
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
的預設初始設定式。 此步驟會實作 Configuration.Provider
,以提供自訂的 'WorkFactory',負責在執行階段期間建立 WorkerManager
。
如果應用程式與 Azure Function 整合,則應用程式參數的初始化應該新增在方法 'onCreate()' 中。 在應用程式啟動之前,會先呼叫方法 'getWorkManagerConfiguration()',再建立任何活動、服務或接收者物件 (不包括內容提供者),以便先初始化應用程式參數再使用。 您可以在範例聊天應用程式中找到更多詳細資料。
- 將使用步驟 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"
>