跳到主要内容

Android集成Websocket消息实时推送

集成Android SDK​

    dependencies {
implementation 'io.goeasy:goeasy-android:0.1.13'
}

Demo源码下载​

Github下载 Gitee下载

初始化GoEasy​

    class App : Application() {

override fun onCreate() {
super.onCreate()

GoEasy.init(
host = "hangzhou.goeasy.io",//新加坡:singapore.goeasy.io
appkey = "您的appkey",
context = applicationContext
)
}
}

建立连接​

        GoEasy.connect()

订阅(接收)消息​

    GoEasy.ws.subscribe(
listOf("demo_channel"),

{ message ->
Log.i("GoEasy", message.content)
}
)

发送消息​

    val options = PublishOptions(
channel = "demo_channel",
content = "hello, world"
)

GoEasy.ws.publish(options)

取消订阅​

   GoEasy.ws.unsubscribe("demo_channel")

断开连接​

    GoEasy.disconnect()

GoEasy连接状态​

获取当前连接状态​

val state =  GoEasy.state;
Log.i("GoEasy", "当前连接状态: $state")

监听连接状态变化​


//监听
GoEasy.onStateChange { event ->
Log.i("GoEasy", "当前状态: ${event.current}, 尝试连接次数: ${event.attempts}, 错误: ${event.error?.let { "[${it.code}] ${it.message}" } ?: "无"}")
}


//取消监听
GoEasy.onStateChange(null)