跳到主要内容

Android 监听器与回调体系

在调用 Open_im_sdk.initSDK 之后、Open_im_sdk.login 之前,需通过 Open_im_sdk.set*Listener 注册各业务监听器。


1. 注册全局监听器​

注册方法 (Open_im_sdk)回调接口 (io.openim.android.open_im_sdk_callback.*)职责说明
setConversationListenerOnConversationListener会话新增、会话变更、总未读数变更、同步状态、对方正在输入状态变更
setAdvancedMsgListenerOnAdvancedMsgListener收到新消息、单聊已读回执、消息撤回、消息删除
setGroupListenerOnGroupListener群资料变更、群成员增删改、加群申请与审批通知
setFriendListenerOnFriendshipListener好友增删改、好友申请与审批、黑名单变更
setUserListenerOnUserListener个人资料更新、已订阅用户在线状态变更 (onUserStatusChanged)
setCustomBusinessListenerOnCustomBusinessListener自定义业务透传通知

2. Kotlin 协程 (suspendCancellableCoroutine) 封装建议​

在 Android Kotlin 层,建议使通用 Base 回调桥接为 suspend 函数(与 iOS QXJIMSDK 的 CheckedContinuation 模式一致):

import io.openim.android.open_im_sdk_callback.Base
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException

class IMException(val code: Int, override val message: String) : Exception("[$code] $message")

suspend inline fun callIMCore(crossinline block: (Base) -> Unit): String =
suspendCancellableCoroutine { cont ->
val callback = object : Base {
override fun onSuccess(data: String?) {
if (cont.isActive) cont.resume(data.orEmpty())
}
override fun onError(errCode: Int, errMsg: String?) {
if (cont.isActive) cont.resumeWithException(IMException(errCode, errMsg.orEmpty()))
}
}
block(callback)
}