You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android后台中Socket.IO无法接收事件问题求助

问题:Android后台LifecycleService无法接收Socket.IO事件?

我已在Android应用中集成Socket.IO,通过后台LifecycleService接收事件,应用处于前台时功能正常。但当应用关闭或进入后台后,虽已确认Socket连接正常,却无法接收事件。需要注意的是,当应用在前台时,收到Socket事件会正常打印日志,但进入后台后则不会打印任何日志。

Service代码

const val SOCKET_EVENT = "message:response"

@AndroidEntryPoint
class MService : LifecycleService() {

    @Inject
    lateinit var ioSocket: Socket

    override fun onCreate() {
        super.onCreate()
        ioSocket.connect()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        super.onStartCommand(intent, flags, startId)
        ioSocket.connect()
        AndroidRemoteDebugger.Log.d("Starting  My Service")
        listenToSocketsEvents()
        return START_STICKY
    }


    private fun listenToSocketsEvents() {
        ioSocket.on(SOCKET_EVENT, onSocketEvent)
    }

    private val onSocketEvent: Emitter.Listener = object : Emitter.Listener {
        override fun call(vararg args: Any?) {
            try {
                val data = args[0] as JSONObject
                //While the main thing about the service is that I'm logging data jhere when I get an 
                // incoming socket event it does log when app is in foreground but when it's in 
                // background it doesn't log
                AndroidRemoteDebugger.Log.v(data.toString())
                val message = data.getJSONObject("message")
                val id = message.getString("id")

                playSound()

                val topic = "message-request"
                val intent = Intent(
                    this@MService,
                    MessageReceiver::class.java
                ).apply {
                    putExtra("messageId", id)
                    putExtra("topic", topic)
                }
                sendBroadcast(intent)
            } catch (e: JSONException) {
                AndroidRemoteDebugger.Log.e(e.message)
                return
            }
        }
    }

    private fun playSound() {
        val notificationSound: Uri =
            Uri.parse(
                (ContentResolver.SCHEME_ANDROID_RESOURCE + "://" +
                        packageName) + "/" + R.raw.car_horn
            )
        val ringtone: Ringtone = RingtoneManager.getRingtone(
            applicationContext,
            notificationSound
        )
        ringtone.play()
    }
}

Receiver代码

class MessageReceiver: BroadcastReceiver() {

    override fun onReceive(context: Context?, intent: Intent?) {
        val topic = intent?.getStringExtra("topic")
        val tripId = intent?.getStringExtra("tripId")
        val intent = Intent(Constants.NOTIFICATION).apply {
            putExtra("Notify", topic)
            putExtra("tripId", tripId)
            putExtra("from", Constants.SOCKETS)
        }
        if (context != null) {
            LocalBroadcastManager.getInstance(context).sendBroadcast(intent)
        }

    }
}

内容的提问来源于stack exchange,提问作者Ezzy Wachira

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 07:41:35