你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

启用推送通知

推送通知可让客户端在移动应用未在前台运行的情况下,获知传入消息和聊天线程中发生的其他操作。 Azure 通信服务支持你可以订阅的事件列表

注意

聊天推送通知支持从版本 1.1.0-beta.4 和 1.1.0 开始的 Android SDK。 建议使用版本 2.0.0 或更高版本,因为旧版本存在与注册续签有关的已知问题。 只有版本 2.0.0 或更高版本才需要步骤 8 到 12。

  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. 在与通信服务资源相同的订阅中创建通知中心,为中心配置 Firebase Cloud Messaging 设置,并将通知中心链接到通信服务资源。 请参阅通知中心预配

  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. 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.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. 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();
        }
    }

对上述代码的说明:在步骤 9 中已禁用了 WorkManager 的默认值初始化表达式。 此步骤实现了 Configuration.Provider 以提供自定义的“WorkFactory”,它负责在运行时创建 WorkerManager

如果应用将与 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"
>