我在 Android studio 的 Android 应用程序中使用 okhttps 创建了一个访问 websocket 的 Web 服务,但该服务给了我错误。 有什么方法可以解决这个问题或者其他方法来访问Android中的websocket
我在 Android 应用程序中有类似的服务
package com.example.acessibilyapp.service
import android.annotation.SuppressLint
import android.app.Service
import android.content.Intent
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.os.Message
import android.util.Log
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.WebSocket
import okhttp3.WebSocketListener
object sebSocketListener : WebSocketListener() {
private val TAG = "Test"
override fun onOpen(webSocket: WebSocket, response: Response) {
super.onOpen(webSocket, response)
webSocket.send("Android Device Connected")
Log.d(TAG, "onOpen:")
}
override fun onMessage(webSocket: WebSocket, text: String) {
super.onMessage(webSocket, text)
Log.d(TAG, "onMessage: $text")
println(text)
}
override fun onClosing(webSocket: WebSocket, code: Int, reason: String) {
super.onClosing(webSocket, code, reason)
Log.d(TAG, "onClosing: $code $reason")
}
override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
super.onClosed(webSocket, code, reason)
Log.d(TAG, "onClosed: $code $reason")
}
override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
Log.d(TAG, "onFailure: ${t.message} $response")
super.onFailure(webSocket, t, response)
}
}
class WebSocketListener: Service() {
override fun onBind(p0: Intent?): IBinder? {
TODO("Not yet implemented")
}
val client = OkHttpClient()
private val okHttpClient = OkHttpClient()
val websocketURL = "wss://free.blr2.piesocket.com/v3/1?api_key=AiaSdPmM1Aw231s3Yq4eOq6E2mbjeu55N2tgqqcd¬ify_self=1"
fun starttes() {
val request = Request.Builder()
.url(websocketURL)
.build()
val websocket = client.newWebSocket(request, sebSocketListener)
Thread.sleep(10000)
websocket.send("Hello")
}
override fun onCreate() {
super.onCreate()
// Initialize resources or perform setup tasks
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
starttes()
return START_STICKY // Return START_STICKY to ensure service persistence
}
override fun onDestroy() {
super.onDestroy()
// Perform cleanup tasks and release resources
}
}
当我致电此服务时
val serviceIntent = Intent(this,WebSocketListener )
这给了我一个错误“分类器‘WebSocketListener’没有伴随对象,因此必须在这里初始化”
您调用了错误的扩展类,而不是您自己的类。
val serviceIntent = Intent(this, sebSocketListener::class.java)
使您的sebSocketListener类名称类似于MySocketListener,这样您就不会感到困惑。