Android Studio应用中生成Azure Communication Services Token遇阻求助
问题诊断与解决方案
1. 连接字符串格式错误
你的connectionString写法存在严重错误,嵌套了多余的<String...>标签,正确的连接字符串是从Azure通信服务门户获取的完整字符串,必须包含endpoint和accesskey两部分,格式示例:
String connectionString = "endpoint=https://agentq-1984.unitedstates.communication.azure.com/;accesskey=你的实际访问密钥";
2. 缺失必要的依赖库
Azure通信服务的身份认证(Identity)与通话(Calling)是独立的SDK,需在Module级别的build.gradle中同时添加以下依赖:
// 身份认证核心SDK implementation 'com.azure.android:azure-communication-identity:1.0.0' // 通话SDK implementation 'com.azure.android:azure-communication-calling:2.0.0' // Azure基础依赖 implementation 'com.azure.android:azure-core:1.0.0'
添加后同步Gradle确保依赖下载完成。
3. 主线程网络调用异常
Android禁止在主线程执行同步网络请求,communicationIdentityClient.createUserAndToken(scopes)属于同步网络操作,直接在UI线程调用会触发NetworkOnMainThreadException。需将身份认证逻辑移至后台线程,以下是基于Coroutine的实现示例:
首先添加Coroutine依赖:
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.4'
修改后的代码:
private void createAgent() { String connectionString = "endpoint=https://agentq-1984.unitedstates.communication.azure.com/;accesskey=你的实际访问密钥"; Context context = getApplicationContext(); // 后台线程执行身份认证 CoroutineScope scope = CoroutineScope(Dispatchers.IO); scope.launch(() -> { try { CommunicationIdentityClient communicationIdentityClient = new CommunicationIdentityClientBuilder() .connectionString(connectionString) .buildClient(); List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.VOIP); CommunicationUserIdentifierAndToken result = communicationIdentityClient.createUserAndToken(scopes); String userToken = result.getUserToken().getToken(); // 回到主线程初始化通话客户端 runOnUiThread(() -> { try { CommunicationTokenCredential credential = new CommunicationTokenCredential(userToken); CallClient callClient = new CallClient(); deviceManager = callClient.getDeviceManager(context).get(); callAgent = callClient.createCallAgent(context, credential).get(); } catch (Exception ex) { Toast.makeText(context, "创建呼叫代理失败:" + ex.getMessage(), Toast.LENGTH_SHORT).show(); } }); } catch (Exception ex) { runOnUiThread(() -> { Toast.makeText(context, "生成令牌失败:" + ex.getMessage(), Toast.LENGTH_SHORT).show(); }); } }); }
4. 必要的权限配置
在AndroidManifest.xml中添加基础网络权限,若涉及语音通话还需添加麦克风相关权限:
<!-- 网络权限 --> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <!-- 语音通话权限 --> <uses-permission android:name="android.permission.RECORD_AUDIO" /> <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
内容的提问来源于stack exchange,提问作者pbhuter
相关产品推荐
相关产品推荐

