我将套接字设置为对象类,如何在另一个片段中调用它?

时间:2019-01-03 02:51:00

标签: android kotlin socket.io

我处理的项目已将套接字设置为名为SocketService.kt的对象类。我想在另一个类上调用套接字发射。我该怎么做?

object SocketService {

    var TAG = SocketService::class.java.simpleName


    fun init() {

        var opts = IO.Options()
        opts.query = "token="+RushOwlApp.getApp().getUserToken()

        var socket = IO.socket(RushOwlApp.getApp().getAppMetaData()?.socketUrl,opts)
        socket.on(Socket.EVENT_CONNECT) {
            Log.i(TAG,"Socket Connected")
            socket.emit("hello")
        }.on(Socket.EVENT_DISCONNECT) {
            Log.i(TAG,"Socket on Disconnect")
            socket.connect()
        }.on("helloResponse"){( args ) ->
            Log.i(TAG,args.toString())
        }

        socket.connect()

     }
}

1 个答案:

答案 0 :(得分:0)

如果在Kotlin中某些类标记为object,则可以通过类名称引用其属性和方法。在您的情况下,它将如下所示:

// Call it from wherever you want
SocketService.init()