移动端 SDK
Android SDK
安装并使用 STINGIM Android SDK:初始化、用户身份、聊天界面、事件与令牌存储。
Android SDK(com.stingim:stingim-channel,版本 1.1.0)提供内置聊天界面,以及用于自定义界面的无界面(headless)API。SDK 使用 Java 编写,可在 Kotlin 中直接调用。
环境要求
| 项目 | 要求 |
|---|---|
minSdk | 23(Android 6.0) |
SDK 使用的 compileSdk / targetSdk | 37 |
| Java 语言级别 | 17 |
| Android Gradle Plugin | 9.3.1(已测试) |
| 主要依赖 | OkHttp 4.12、Gson、Room 2.8、Glide 5、EventBus、PhotoView、AndroidX AppCompat / Material / RecyclerView |
安装
SDK 发布在本站的 STINGIM Maven 仓库中,无需账号或凭据。在 google() 和 mavenCentral() 旁加入该仓库:
dependencyResolutionManagement {
repositories {
google()
mavenCentral()
maven { url "https://stingim.com/sdk/maven" }
}
}dependencies {
implementation 'com.stingim:stingim-channel:1.1.0'
}使用 Kotlin DSL 时:
dependencyResolutionManagement {
repositories {
google()
mavenCentral()
maven { url = uri("https://stingim.com/sdk/maven") }
}
}dependencies {
implementation("com.stingim:stingim-channel:1.1.0")
}仓库提供 AAR、sources JAR、POM、Gradle module metadata 以及 md5/sha1/sha256/sha512 校验文件,Android Studio 可直接查看 SDK 源码。传递依赖从 google() 和 mavenCentral() 解析;唯一不在 Maven Central 上的 PhotoView 2.3.0 已原样镜像在同一仓库,无需 JitPack。如果你的工程仍使用旧式 allprojects { repositories { … } },把 maven { url "https://stingim.com/sdk/maven" } 加在那里即可。
直接下载 AAR
无法使用 Maven 仓库时,下载 stingim-channel-1.1.0.aar,并与下载页上的 SHA-256 核对。单独的 AAR 不包含依赖信息,需要自行声明 SDK 的依赖(PhotoView 需要 maven { url "https://stingim.com/sdk/maven" } 或 JitPack):
dependencies {
implementation files('libs/stingim-channel-1.1.0.aar')
implementation 'androidx.core:core-ktx:1.19.0'
implementation 'androidx.appcompat:appcompat:1.8.0'
implementation 'com.google.android.material:material:1.14.0'
implementation 'androidx.constraintlayout:constraintlayout:2.2.2'
implementation 'androidx.recyclerview:recyclerview:1.4.0'
implementation 'androidx.room:room-runtime:2.8.4'
implementation 'com.squareup.okhttp3:okhttp:4.12.0'
implementation 'com.squareup.okhttp3:logging-interceptor:4.12.0'
implementation 'com.google.code.gson:gson:2.14.0'
implementation 'org.greenrobot:eventbus:3.3.1'
implementation 'com.orhanobut:logger:2.2.0'
implementation 'com.github.bumptech.glide:glide:5.0.9'
implementation 'com.github.chrisbanes:PhotoView:2.3.0'
}推荐使用 Maven 方式:依赖列表与源码都会自动获取。
初始化
生产环境:从服务端获取 token
你的服务端用 App Secret 换取访客 token(方法),并将 contactId、contactToken 和 channelId 返回给应用:
Stingim.initWithToken(this, contactId, contactToken, channelId,
tenantId, projectId, new Stingim.InitCallback() {
@Override public void onSuccess(String contactId, String token) {
Stingim.startChat(MainActivity.this, "在线客服");
}
@Override public void onError(String error) { /* 显示错误 */ }
});tenantId 和 projectId 为可选参数;也提供五参数重载 initWithToken(context, contactId, contactToken, channelId, callback)。
开发环境:由 SDK 换取 App Secret
仅适用于开发或受控环境。请勿在正式发布的应用中硬编码 App Secret。
import com.stingim.Stingim;
Stingim.init(this, "your_plugin_id", "your_app_secret", "your_channel_id",
new Stingim.InitCallback() {
@Override
public void onSuccess(String contactId, String token) {
// 初始化完成;WebSocket 会自动连接
Stingim.startChat(MainActivity.this, "在线客服"); // 打开内置聊天界面
}
@Override
public void onError(String error) {
// 凭证错误、网络错误等
}
});以不同身份再次初始化会失败并报错 SDK is already initialized with a different identity; disconnect first,请先调用 Stingim.disconnect()。
配置
请在 init 之前调用 setConfig:
StingimConfig config = new StingimConfig()
.setApiBaseUrl("https://api.stingim.com") // REST 基础地址(默认值)
.setSocketBaseUrl("wss://msg.stingim.com") // 网关基础地址(默认值;会自动追加 /visitor)
.setDebugMode(true);
Stingim.setConfig(config);
Stingim.init(this, pluginId, appSecret, channelId, callback);其他选项:setProjectId(直连模式下显示 AI 身份提示和营业时间提示时需要)、autoConnect、showNotification、playSoundOnMessage、vibrateOnMessage、heartbeatInterval(仅作兜底,以服务端下发的值为准)、reconnectAttempts、reconnectDelay。
用户身份
要将已登录用户绑定到客户(使历史记录跨设备同步),请在服务端按与网页挂件完全相同的方式签名:user_hash = hex(HMAC-SHA256(secret, user_id));如需设置过期时间,则对 user_id + ":" + exp 签名。
生产环境中,由服务端将签名字段发送给 open-create-contact(换取 token)。直连模式下,将其传给 SDK:
StingimIdentity identity = StingimIdentity.builder(userId, userHash)
.userHashExp(exp) // 仅当签名内容为 "user_id:exp" 时设置
.userName("Jane Doe") // 仅用于展示,不在签名范围内
.userEmail("[email protected]")
.build();
Stingim.init(context, pluginId, appSecret, channelId, identity, callback);
Stingim.getIdentityStatus(); // anonymous / verified / unverified / rejected
Stingim.isIdentityVerified();用户退出登录时,调用 Stingim.disconnect()。initWithUser(...) 已弃用:单纯的用户 ID 不能作为凭证。
内置聊天界面
Stingim.startChat(context); // 默认标题
Stingim.startChat(context, "在线客服"); // 自定义标题startChat 会打开 ChatActivity;如果 SDK 尚未初始化,会抛出 IllegalStateException。该界面支持文本、表情、图片、文件、语音消息、交互按钮、排队位置以及满意度评价弹窗。界面文案默认为英文,并附带中文(values-zh)翻译;覆盖任意 stingim_* 字符串资源即可修改文案。内置样式为 Theme.STINGIM.Chat 和 Theme.STINGIM.ImagePreview。
自定义界面
自行构建界面时,请使用各管理器。所有回调都在主线程执行。
StingimConversationManager conv = StingimConversationManager.getInstance(context);
StingimMessageManager msg = StingimMessageManager.getInstance(context);
conv.startChat(title, startCallback);
String conversationId = conv.effectiveConversationId();
msg.sendTextMessage(conversationId, "Hello");
msg.fetchServerHistory(30, historyCallback);
msg.loadMessages(conversationId, offsetId, pageSize, pageCallback);
msg.markAsRead(conversationId, lastMessageId);
msg.sendTyping(conversationId);
// 交互消息(按钮)
StingimInteractive card = message.getInteractive();
msg.sendInteractionReply(message, card.getActions().get(0));
// 文件:先上传,再发送
StingimFileService files = StingimFileService.getInstance(context);
files.upload(file, "photo.jpg", "image/jpeg", uploadCallback); // onUploaded → msg.sendMediaMessage(conversationId, uploaded)
files.resolvePreviewUrl(message.getContent(), previewCallback); // 获取收到的媒体的签名 URL
// 排队与未读
conv.getQueueInfo(conversationId, queueCallback);
conv.getUnreadCount(conversationId, unreadCallback);发送第一条消息前还没有会话;SDK 会先使用临时 ID 发送,并自动切换到真实的会话 ID。
事件与监听器
| 监听器 | 方法 |
|---|---|
StingimMessageManager.MessageListener | onMessageAdded(StingimMessage)、onMessageListChanged() |
StingimMessageManager.MessageStatusListener | onMessageStatusChanged(StingimMessage),包括 rate_limited |
StingimMessageManager.EvaluationListener | onEvaluationInvite(StingimEvaluationInvite)、onEvaluationSubmitted(StingimEvaluation)、onEvaluationComplete(String) |
StingimMessageManager.TypingListener | onTypingStatusChanged(conversationId, userId, userName, userType, isTyping) |
StingimSocketClient.ConnectionListener | onConnected()、onDisconnected(String)、onError(String)、onOnlineSuccess() |
StingimSocketClient.QueueListener | onQueueStatusUpdate(...)、onConversationStatusChanged(String, int)、onRobotAccess(String, boolean) |
StingimSocketClient.MessageListener | onReceiveMessage(...)、onMessageError(...)、onResync(...)、onReady()、onStreamDelta(...)(AI 流式回复) |
StingimConversationManager.ConversationListener | onConversationChanged(...)、onQueueStatusChanged(...) |
StingimAuthListener | onTokenInvalid(StingimError)、onReauthenticated(String contactId, boolean contactChanged)、onReauthenticationFailed(StingimError) |
token 生命周期
Stingim.setAuthListener(new StingimAuthListener() {
@Override public void onTokenInvalid(StingimError error) { /* 例如 "session expired" */ }
@Override public void onReauthenticated(String contactId, boolean contactChanged) { }
@Override public void onReauthenticationFailed(StingimError error) {
// token 模式:从服务端获取新 token,然后调用 Stingim.initWithToken(...)
}
});StingimError.Code:TOKEN_INVALID、IDENTITY_REJECTED、SESSION_EVICTED、RATE_LIMITED、NETWORK、SERVER、INVALID_ARGUMENT、UNSUPPORTED。
- 被拒绝的 token(HTTP 401、业务码 502 或网关返回
unauthorized)会被清除。直连模式下 SDK 会自动重新引导;token 模式下,请获取新 token 并再次调用initWithToken。 session_evicted(同一访客在其他地方建立了连接)不会自动重连。
token 存储
访客 token 使用 Android Keystore 中不可导出的 AES-256-GCM 密钥加密,存储在 SDK 私有的 SharedPreferences 中。若 Keystore 不可用,token 仅保存在内存中。在新设备上恢复的备份无法解密该 token,此时 SDK 会直接开始新会话。Stingim.disconnect() 会清除 token 和身份信息。消息缓存在本地 Room 数据库中。日志中绝不会包含 token、App Secret 或完整的消息帧。
生命周期辅助方法
Stingim.isInitialized();
Stingim.isConnected();
Stingim.connect(); // autoConnect 为 false 时使用
Stingim.disconnect(); // 断开连接并清除本地鉴权数据,退出登录时调用
Stingim.getVersion(); // "1.1.0"权限与 Manifest
SDK 的 manifest 会合并以下内容:INTERNET、ACCESS_NETWORK_STATE、RECORD_AUDIO(语音消息)、VIBRATE、POST_NOTIFICATIONS 和 WRITE_EXTERNAL_STORAGE(仅 API ≤ 28),authority 为 ${applicationId}.fileprovider 的 FileProvider,以及未导出的 ChatActivity / ImagePreviewActivity。使用相关功能前,请先申请运行时权限(麦克风;Android 13+ 的通知权限)。使用明文 HTTP 的测试服务器需要设置 android:usesCleartextTraffic="true";生产环境仅使用 HTTPS/WSS。
R8/ProGuard:SDK 自带 consumer rules(-keep class com.stingim.** { *; }),无需额外配置。
1.0 暂不支持
- 引用回复:
sendReplyMessage会以纯文本发送。 StingimApi.getConversationDetail(后端仅对客服开放)。
如遇问题,请参阅故障排查。
发现错误?请发邮件至 [email protected]
