Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
68 views
in Technique[技术] by (71.8m points)

SENDBIRD KOTLIN message

I am using the SENDBIRD SDK on Android to implement a chat in flutter using platformsChannels.

I have managed to implement the connection, create channels, and send messages, but when I send a message from another device it does not run in the onMessageReceived () method. I am putting the following code in a onCall method to run from Dart, after creating the channel and entering it.

var channelUrl: String? = call.argument("urlChannel")

    GroupChannel.getChannel(channelUrl,
            GroupChannelGetHandler { groupChannel, err ->
              if (err != null) {
                result.error("420", "$err", null)
              } else{
                this.groupChannel = groupChannel
                val jsonConvertData: String? = Gson().toJson(groupChannel)
                println(jsonConvertData)
                result.success(jsonConvertData)
              }
            })

        SendBird.addChannelHandler(
              CHANNEL_HANDLER_ID,
              object : ChannelHandler() {
                  override fun onMessageReceived(
                      baseChannel: BaseChannel,
                      baseMessage: BaseMessage
                  ){
                    println("$baseMessage")
                     }

                  }
              })

My goal is to print to console the message that has been received but for now I only get the message from the internal socket in SENDBIRD. As shown in the picture.

enter image description here

I came to the conclusion that onMessageRecived is not being executed, and my question is if there is any way to access the data that the socket brings me.

UPDATE

This is all code in mi file

package com.example.send_bird


import android.content.Context
import android.content.Intent
import android.os.AsyncTask
import android.util.Log
import android.widget.Toast
import androidx.annotation.NonNull
import com.google.gson.Gson
import com.sendbird.android.*
import com.sendbird.android.BaseChannel.SendUserMessageHandler
import com.sendbird.android.GroupChannel.GroupChannelGetHandler
import com.sendbird.android.SendBird.ChannelHandler
import io.flutter.app.FlutterActivity
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import java.util.*


/** SendBirdPlugin */
class SendBirdPlugin: FlutterActivity(),FlutterPlugin, MethodCallHandler {
  /// The MethodChannel that will the communication between Flutter and native Android
  ///
  /// This local reference serves to register the plugin with the Flutter Engine and unregister it
  /// when the Flutter Engine is detached from the Activity
  private lateinit var channel : MethodChannel
  private lateinit var groupChannel: GroupChannel
  private val CHANNEL = "ec.tipti/sendbird"
  private lateinit var context: Context
  private val CHANNEL_HANDLER_ID = "CHANNEL_HANDLER_GROUP_CHANNEL_CHAT"

  override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
    channel = MethodChannel(flutterPluginBinding.binaryMessenger, CHANNEL)
    channel.setMethodCallHandler(this)
    context = flutterPluginBinding.applicationContext



  }

  override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
    when (call.method) {
      //**Init SendBird
      "initSendBird" -> {
        try {
          var appId: String? = call.argument("appId")
          var response: Boolean = SendBird.init(appId, context);
          result.success(response)

        } catch (err: Error) {
          println("THIS ERR $err")
          result.error("404", err.message, err.stackTrace)
        }

      }
      //Connect to sendbirdserver
      "connectToSendBirdServer" -> {
        // The userID below should be unique to your Sendbird application.
        var userID: String? = call.argument("userId")
        try {
          SendBird.connect(userID) { user, err ->
            if (err != null) {
              result.error(err.code.toString(), "${err.message}", "${err.stackTrace}")
            } else {
              val jsonConvertData: String? = Gson().toJson(user)
              result.success(jsonConvertData)
            }
          }
        } catch (err: Error) {
          result.error("404", "${err.message}", "${err.stackTrace}")
        }

      }

      "getListChannel" -> {
        val channelList = GroupChannel.createMyGroupChannelListQuery()
        channelList.limit = 100
        channelList.next { list, e ->
          if (e != null) {
            Log.e("TAG", e.message)
          }
          val jsonConvertData: String? = Gson().toJson(list)
          result.success(jsonConvertData)
        }
      }

      "createPrivateChannel" -> {
        val users: List<String>? = call.argument("users")
        val params = GroupChannelParams()
        val operatorId = ArrayList<String>()
        operatorId.add(SendBird.getCurrentUser().userId)
        params.addUserIds(users)
        params.setOperatorUserIds(operatorId)
        GroupChannel.createChannel(params) { groupChannel, err ->
          if (err != null) {
            println("FAIL TO CREATE CHANEL")
            result.error("420", "$err", null)
          } else {

            val jsonConvertData: String? = Gson().toJson(groupChannel)
            result.success(jsonConvertData)
          }
        }
      }

      "enterChannel" -> {
        var channelUrl: String? = call.argument("urlChannel")

        GroupChannel.getChannel(channelUrl,
                GroupChannelGetHandler { groupChannel, err ->
                  if (err != null) {
                    result.error("420", "$err", null)
                  } else {
                    this.groupChannel = groupChannel
                    val jsonConvertData: String? = Gson().toJson(groupChannel)
                    println(jsonConvertData)
                    result.success(jsonConvertData)
                  }
                })
        SendBird.addChannelHandler(
                CHANNEL_HANDLER_ID,
                object : ChannelHandler() {
                  override fun onMessageReceived(
                          baseChannel: BaseChannel?,
                          baseMessage: BaseMessage?
                  ) {
                    println("Message")
                    if (!baseChannel?.url.equals("sendbird_group_channel_84227333_d808b92bbf2107ef8b9eb97012bb73126aefd462")) {
                      println("MESSAGE!!!!!!!!!!!!!!!")
                    }
                  }
                })

      }
      "startHandler" -> {
        println("START HANDLER")
        val value = ListenMessage()
        val intent = Intent(context, ListenMessage::class.java)
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        context.startActivity(intent)
//          context.startService(intent)


      }
      "sendMessageToChannel" -> {
        var msj: String? = call.argument("message")
        println(msj)
        val params = UserMessageParams()
                .setMessage(msj.toString())
        groupChannel.sendUserMessage(params,
                SendUserMessageHandler { userMessage, err ->
                  if (err != null) {
                    result.error("420", "$err", null)
                  }

                  println(userMessage)
                })
      }
      "pauseChannelHandler" -> {
        var channelHandlerID: String? = call.argument("channelHandlerId")
        SendBird.removeChannelHandler(CHANNEL_HANDLER_ID)
      }
      "getPreviusMessage" -> {

        val previousMessageListQuery = groupChannel.createPreviousMessageListQuery()

        previousMessageListQuery.load(
                20,
                true,
                object : PreviousMessageListQuery.MessageListQueryResult {
                  override fun onResult(
                          messages: MutableList<BaseMessage>?,
                          e: SendBirdException?
                  ) {
                    if (e != null) {
                      Log.e("Error", e.message)
                    }
                    val jsonConvertData: String? = Gson().toJson(messages)
                    result.success(jsonConvertData)
                  }
                })


      }
      else -> {
        result.notImplemented()
      }
    }
  }


  override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
    channel.setMethodCallHandler(null)
  }


}

I've been working on this and managed to hear the onMessage when starting a new activity. My question is now is there a way to start an activity without the need for a screen to be shown to me? This is the code for my second activity.

package com.example.send_bird

import com.sendbird.android.BaseChannel
import com.sendbird.android.BaseMessage
import com.sendbird.android.SendBird
import io.flutter.app.FlutterActivity


class ListenMessage: FlutterActivity() {
    private val CHANNEL_HANDLER_ID = "CHANNEL_HANDLER_GROUP_CHANNEL_CHAT"

    override fun onResume() {
        super.onResume()
        println("ENTER TO LISTEN MESSAGE")
        SendBird.addChannelHandler(
                CHANNEL_HANDLER_ID,
                object : SendBird.ChannelHandler() {
                    override fun onMessageReceived(
                            baseChannel: BaseChannel,
                            baseMessage: BaseMessage
                    ){
                        println("$baseMessage")
                    }
                })
    }



}

I have tried using Services () and Async () but as the first time I can't hear the onMessage ()

question from:https://stackoverflow.com/questions/65833738/sendbird-kotlin-message

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...