Android 在前台服务中丢失 websocket 连接

问题描述

我使用 websocket 连接到我的服务器来接收/发送特定消息。 消息还带有通知

建立连接后一切正常。当我从服务器向应用程序发送消息并且一切正常时会显示推送通知,但是当我在 30 分钟或更长时间后再次尝试并将消息从我的服务器发送到应用程序时没有任何反应。 从我在日志中看到的应用程序和服务器套接字连接都没有断开:/。

发生这种情况有什么原因吗?

我是否必须每分钟 ping 一次服务器才能保持连接正常运行?

这是我用来启动服务的代码

主活动

...
    override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            val myServiceIntent = Intent(this,ForegroundSocket::class.java)
            ContextCompat.startForegroundService(this,myServiceIntent)
    }
...

前台套接

...
    // Binder given to clients (notice class declaration below)
    private var notification: Notification? = null
    private val mBinder: mybinder = mybinder()

    // Channel ID for notification
    val CHANNEL_ID = "Random number notification"

    /**
     * Class used for the client Binder. The Binder object is responsible for returning an instance
     * of "MyService" to the client.
     */
    inner class mybinder : Binder() {
        // Return this instance of MyService so clients can call public methods
        val service: ForegroundSocket
            get() =// Return this instance of MyService so clients can call public methods
                this@ForegroundSocket
    }

    /**
     * This is how the client gets the IBinder object from the service. It's retrieve by the "ServiceConnection"
     * which you'll see later.
     */
    override fun onBind(intent: Intent): IBinder? {
        return mBinder
    }

    /**
     * Called when service is created So  we will do our work here
     */
    override fun onCreate() {
        super.onCreate()
        Log.d("MyBoundService","onCreate called")
        startNotification()
    }

    /**
     * Used for creating and starting notification
     * whenever we start our Bound service
     */
    private fun startNotification() {
        val channel = NotificationChannel(
            CHANNEL_ID,"My Channel",notificationmanager.IMPORTANCE_DEFAULT
        )

        (getSystemService(Context.NOTIFICATION_SERVICE) as notificationmanager).createNotificationChannel(
            channel
        )
        notification = NotificationCompat.Builder(this,CHANNEL_ID)
            .setSmallIcon(R.drawable.ic_lock_outline)
            .setTicker("Ticker text")
            .setContentTitle("A service is running in the background")
            .setContentText("Generating random number")
            .build()
        startForeground(1,notification)
    }

}
...

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...