Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

how to send and receive messages in rtm #83

Closed
Nader2004 opened this issue May 23, 2022 · 9 comments
Closed

how to send and receive messages in rtm #83

Nader2004 opened this issue May 23, 2022 · 9 comments

Comments

@Nader2004
Copy link

Hello I have been trying to send and receive message through the AgoraRtmChannel Object. But whenever i listen to messages through the onMessageReceived, it tells me that I called the onMessageReceived on null,

Here is the code:

` The client is already initialized and I have also provided a username to  use RTM`
_channel = client.sessionController.value.agoraRtmChannel;
_channel.onMessageReceived = (rtmMessage, member) {
      print(rtmMessage.text);
    };

Here is the error :

The setter 'onMessageReceived=' was called on null.
Receiver: null
Tried calling: onMessageReceived=Closure: (AgoraRtmMessage, AgoraRtmMember) => Null
@Meherdeep
Copy link
Contributor

Hey @Nader2004 , Inside your AgoraClient you can use agoraRtmChannelEventHandler to call any callback from the Agora RTM Channel class.

@Nader2004
Copy link
Author

Hey @Meherdeep thanks for replying, I have tried looking for a named argument that have to do anything with rtm messages but couldn't find one except two that are about rtm :

agoraEventHandlers: AgoraEventHandlers(
        rtmpStreamingEvent: ,
        rtmpStreamingStateChanged: ,
     ),

Also how can I send messages then using rtm from UIKit.

@Nader2004
Copy link
Author

Hey @Meherdeep thanks for the package update. But is still actually facing the problem of sending messages, when I call sendMessage from AgoraRtmChannel like that : client.sessionController.value.agoraRtmChannel.sendMessage( AgoraRtmMessage.fromText(text));, it fails with error code 102, which according to the agora documentation is about rtm login issue. So is this the right way to send a message or how to resolve that error? Thanks!

@Meherdeep
Copy link
Contributor

You can do a check before sending a message to see if the user has logged in or not.

if(client.sessionController.value.isLoggedIn) {
      client.sessionController.value.agoraRtmChannel.sendMessage(message)
    }

@Nader2004
Copy link
Author

hey @Meherdeep I apologize for the late response, I have added the if check but the error still exist. But I did extra observation on the error and discovered that by calling : client.initialize() , it doesn't actually call the Rtm login method.
Here is the code of the initialize() method:

Future<void> initialize() async {
    if (_initialized) {
      return;
    }

    try {
      await _sessionController.initializeEngine(
          agoraConnectionData: agoraConnectionData);
    } catch (e) {
      log("Error while initializing Agora RTC SDK", level: Level.error.value);
    }

    if (agoraConnectionData.rtmEnabled) {
      try {
        await _sessionController.initializeRtm(
            agoraRtmClientEventHandler ?? AgoraRtmClientEventHandler());
      } catch (e) {
        log("Error while initializing Agora RTM SDK. ${e.toString()}",
            level: Level.error.value);
      }
    }

    if (agoraChannelData?.clientRole == ClientRole.Broadcaster ||
        agoraChannelData?.clientRole == null) {
      await _sessionController.askForUserCameraAndMicPermission();
    }
    if (enabledPermission != null) {
      await enabledPermission!.request();
    }

    _sessionController.createEvents(
      agoraRtmChannelEventHandler ?? AgoraRtmChannelEventHandler(),
      agoraEventHandlers ?? AgoraRtcEventHandlers(),
    );

    if (agoraChannelData != null) {
      _sessionController.setChannelProperties(agoraChannelData!);
    }

    await _sessionController.joinVideoChannel();
    _initialized = true;
  }

The important part here is the :

if (agoraConnectionData.rtmEnabled) {
      try {
        await _sessionController.initializeRtm(
            agoraRtmClientEventHandler ?? AgoraRtmClientEventHandler());
      } catch (e) {
        log("Error while initializing Agora RTM SDK. ${e.toString()}",
            level: Level.error.value);
      }
    }

When calling initializeRtm() only the RtmClient is created but there is no callback for the login method:

Future<void> initializeRtm(
      AgoraRtmClientEventHandler agoraRtmClientEventHandler) async {
    value = value.copyWith(
      agoraRtmClient: await AgoraRtmClient.createInstance(
        value.connectionData!.appId,
      ),
    );
    if (value.agoraRtmClient != null) {
      addListener(() {
        createRtmClientEvents(agoraRtmClientEventHandler);
      });
    }
  }

It's just a speculation, maybe the login() method is called elsewhere, I don't know, but the error actually still exists.

@Meherdeep
Copy link
Contributor

Hey @Nader2004, the Rtm login occurs once the user joins the RTC channel. Hence, it's called under the joinChannelSuccess callback.
Can you share your code where you're trying to send a message and your flutter doctor

@Nader2004
Copy link
Author

Okay @Meherdeep here is my sample code :

TextEditingController _channelMessageController;
Future<void> _agoraFuture;
AgoraRtmClient rtmClient;
List<String> _messages = []; 

@override
  void initState() {
    _channelMessageController = TextEditingController();
    _agoraFuture = initAgora();
    super.initState();
  }

Future<void> initAgora() async {
    client = AgoraClient(
      agoraChannelData: AgoraChannelData(
        channelProfile: ChannelProfile.LiveBroadcasting,
        clientRole: widget.clientRole,
      ),
      agoraConnectionData: AgoraConnectionData(
        appId: config.appId,
        channelName: widget.channelName,
        tempToken: config.token,
        rtmChannelName: widget.channelName,
        username: _user.username,
      ),
      agoraRtmClientEventHandler: AgoraRtmClientEventHandler(
        onMessageReceived: (message, uid) {
          _messages.add(message.text);
        },
      ),
      agoraRtmChannelEventHandler: AgoraRtmChannelEventHandler(
        onMessageReceived: (rtmMessage, member) {
          _messages.add(rtmMessage.text);
        },
        onMemberJoined: (member)  {
          _messages.add(member.userId + 'joined the channel');
        },
        onMemberLeft: (member)  {
          _messages.add(member.userId + 'left the channel');
        },
      ),
      enabledPermission: [
        Permission.camera,
        Permission.microphone,
      ],
    );
    await client.initialize();
  }

Widget _buildBottomPart() {
    return Align(
      alignment: Alignment.bottomCenter,
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          _buildListScrollView(),
          Container(
            color: Colors.white.withOpacity(0.5),
            height: 1,
            width: MediaQuery.of(context).size.width,
          ),
          Container(
            alignment: Alignment.bottomRight,
            child: Padding(
              padding: const EdgeInsets.symmetric(
                horizontal: 8,
                vertical: 3,
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: <Widget>[
                  Expanded(
                    child: Padding(
                      padding: const EdgeInsets.fromLTRB(0.0, 0, 0, 0),
                      child: TextField(
                        cursorColor: Colors.blue,
                        textInputAction: TextInputAction.send,
                        onSubmitted: (text) {
                          if (client.sessionController.value.isLoggedIn) {
                            client.sessionController.value.agoraRtmChannel
                                .sendMessage(
                              AgoraRtmMessage.fromText(text),
                            );
                          }
                          
                          _channelMessageController.clear();
                        },
                        style: TextStyle(color: Colors.white),
                        controller: _channelMessageController,
                        textCapitalization: TextCapitalization.sentences,
                        decoration: InputDecoration.collapsed(
                          hintText: 'Comment..',
                          hintStyle: TextStyle(color: Colors.white),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

@override
  void dispose() {
    _channelMessageController.dispose();
    super.dispose();
  }
 
@override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: _agoraFuture,
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return Center(
            child: CircularProgressIndicator(),
          );
        }
        return Stack(
          children: [
            AgoraVideoViewer(
              client: client,
            ),
            _buildBottomPart(),
          ],
        );
      },
    );
  }

And here is the doctor :

[√] Flutter (Channel stable, 3.0.0, on Microsoft Windows [Version 10.0.19043.1706], locale en-US)
[!] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
    X cmdline-tools component is missing
      Run `path/to/sdkmanager --install "cmdline-tools;latest"`
      See https://developer.android.com/studio/command-line for more details.
    X Android license status unknown.
      Run `flutter doctor --android-licenses` to accept the SDK licenses.
      See https://flutter.dev/docs/get-started/install/windows#android-setup for more details.
[√] Chrome - develop for the web
[!] Visual Studio - develop for Windows (Visual Studio Build Tools 2017 15.9.27)
    X Visual Studio 2019 or later is required.
      Download at https://visualstudio.microsoft.com/downloads/.
      Please install the "Desktop development with C++" workload, including all of its default components
[√] Android Studio (version 3.3)
[√] VS Code (version 1.67.2)
[√] Connected device (3 available)
[√] HTTP Host Availability

! Doctor found issues in 2 categories.

@Meherdeep
Copy link
Contributor

Hey @Nader2004 Sorry for the late reply. I tried building the sample code that you shared, I just made a small adjustment to the sendMessage logic and I was able to send messages using that. Here's the code for that:

if (client.sessionController.value.isLoggedIn &&
                              client.sessionController.value.isInChannel) {
                            client.sessionController.value.agoraRtmChannel
                                .sendMessage(
                              AgoraRtmMessage.fromText(text),
                            );
                          }

@Meherdeep
Copy link
Contributor

Closing this issue for now. If you're still facing this issue feel free to reopen it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants