我在服务和活动中使用 WebRTC 库。在两个组件的“onDestroy”中,我尝试完全断开连接,以便在服务/活动再次运行时,设备可以使用相同的过程加入房间。
public void onDestroy() {
for (Peer peer : peers.values()) {
peer.pc.dispose();
}
videoSource.dispose();
factory.dispose();
client.off();<---- You need to turn OFF and then disconnect and then close it.
client.disconnect();
client.close();
}
但是活动/服务因此错误而崩溃(我的代码中没有泄漏):
Channel is unrecoverably broken and will be disposed!
然后我了解到处理连接和工厂可以弥补这个错误。所以我只是将它们设置为空。 onDestroy 回调结果是这样的:
if(videoTrackFromCamera != null) videoTrackFromCamera.dispose();
//if(rootEglBase != null) rootEglBase.release(); //Causes Crash:: # Fatal error in ../../webrtc/sdk/android/src/jni/peerconnection_jni.cc, line 1031
// # last system error: 0
// # Check failed: 0 == (reinterpret_cast<MediaStreamInterface*>(j_p))->Release() (0 vs. 2)
// # Unexpected refcount.
if(audioSource != null) audioSource.dispose();
if(localAudioTrack != null) localAudioTrack.dispose();
if(localMediaStream != null) localMediaStream.dispose();
if(mRemoteMediaStream != null) mRemoteMediaStream.dispose();
audioConstraints = null;
if (factory != null) {
factory.stopAecDump();
}
if (peerConnection != null) {
//peerConnection.dispose();
//peerConnection.close();
peerConnection = null;
}
if (factory != null) {
//factory.dispose(); //causes error Channel is unrecoverably broken and will be disposed
factory = null;
}
if (socket != null) {
sendMessage("finished");
socket.disconnect();
socket.close();
}
现在一切都很好,只是有时我会因此错误而崩溃:
Channel {0} was not shutdown properly!!! ~*~*~*
Make sure to call shutdown()/shutdownNow() and wait until awaitTermination() returns true.
java.lang.RuntimeException: ManagedChannel allocation site
有没有更好的方法来结束WebRTC连接? 如果我想留在房间里但停止发送和/或接收流,最佳方法是什么?
最后,我找到了一个解决方案,如何正确关闭并重新打开连接而不崩溃:)我使用 https://github.com/GetStream/webrtc-in-jetpack-compose/tree/main/webrtc-android 作为良好的起点,这里已经实现了很多逻辑(如音频)。
localAudioTrack.setEnabled(false)
localVideoTrack.setEnabled(false)
audioHandler.stop() // See https://github.com/GetStream/webrtc-in-jetpack-compose/blob/main/webrtc-android/app/src/main/kotlin/io/getstream/webrtc/sample/compose/webrtc/audio/AudioHandler.kt#L69
videoCapturer.stopCapture()
remoteVideoTrackFlow.replayCache.forEach { it.setEnabled(false) } // Disable remote videoTrack
peerConnection.onTrack(null)
peerConnection.onRemoveTrack(null)
peerConnection.onIceCandidate(null)
peerConnection.onIceConnectionChange(null)
peerConnection.onSignalingChange(null)
// And finally close connection
peerConnection.close()
最重要的部分你不需要关闭/处置
PeerConnectionFactory
,因为它会导致我的情况崩溃。
只需重新创建
peerConnectionFactory.makePeerConnection
新的对等连接。就我而言,我只是从上面的库重新创建WebRtcSessionManagerImpl
(https://github.com/GetStream/webrtc-in-jetpack-compose/blob/main/webrtc-android/app/src/main/kotlin/io /getstream/webrtc/sample/compose/webrtc/sessions/WebRtcSessionManagerImpl.kt)