アレックス アレックス - 2 months ago 55
Android Question

Working with DataChannel in Android WebRTC application

Due to the breaking changes in Android WebRTC client's example, I'm looking for the code-example which shows how to add and work with DataChannel in Android. I need to just send "Hello Worlds" via DataChannel between 2 Android devices. Here's the old code:

https://chromium.googlesource.com/external/webrtc/stable/talk/+/master/examples/android/src/org/appspot/apprtc/AppRTCDemoActivity.java#177

It uses some classes and interfaces which don't exist in the new version anymore.

So how can I add support of DataChannel to my Android WebRTC application, send and receive a text through it?

Answer

I added DataChannel in a project with an older version of webrtc. I looked at the most up to date classes and it seems the methods and callbacks are still there, so hopefully it will work for you.

Changes to PeerConnectionClient:

Create DataChannel in createPeerConnectionInternal after isInitiator = false;:

DataChannel.Init dcInit = new DataChannel.Init();
dcInit.id = 1;
dataChannel = pc.createDataChannel("1", dcInit);;
dataChannel.registerObserver(new DcObserver());

Changes to onDataChannel:

@Override 
public void onDataChannel(final DataChannel dc) {
    Log.d(TAG, "onDataChannel");
    executor.execute(new Runnable() {
        @Override
        public void run() {
            dataChannel = dc;
            String channelName = dataChannel.label();
            dataChannel.registerObserver(new DcObserver());
        }
    });
}

Add the channel observer:

private class DcObserver implements DataChannel.Observer {

    @Override 
    public void onMessage(final DataChannel.Buffer buffer) {

        ByteBuffer data = buffer.data; 
        byte[] bytes = new byte[data.remaining()];
        data.get(bytes);
        final String command = new String(bytes);

        executor.execute(new Runnable() {
            public void run() {
                events.onReceivedData(command);
            }
        });

    }

    @Override
    public void onStateChange() {
        Log.d(TAG, "DataChannel: onStateChange: " + dataChannel.state());
    }
}

I added onReceivedDataevents to PeerConnectionEvents interface and all the events are implemented in the CallActivity so I handle the data received on the channel from there.

To send data, from CallActivity:

public void sendData(final String data) {

    ByteBuffer buffer = ByteBuffer.wrap(data.getBytes());
    peerConnectionClient.getPCDataChannel().send(new DataChannel.Buffer(buffer, false));


}

I only took a quick look at the new classes and made minor changes to my code, I hope it will work for you with no more changes.

Good luck

Comments