Sobes.tech
Junior — Middle

How to implement automatic network request sending with a 5-second interval?

sobes.tech AI

Answer from AI

To automatically send network requests at 5-second intervals on Android, you can use the Handler class with the postDelayed method or Timer.

Example using Handler:

val handler = Handler(Looper.getMainLooper())

val runnable = object : Runnable {
    override fun run() {
        // Here perform the network request
        sendNetworkRequest()
        // Restart after 5 seconds
        handler.postDelayed(this, 5000)
    }
}

// Start
handler.post(runnable)

// To stop
// handler.removeCallbacks(runnable)

fun sendNetworkRequest() {
    // Implementation of network request, e.g., via Retrofit or OkHttp
}

You can also use Timer and TimerTask, but Handler is preferred for UI thread operations. Modern applications often use coroutines with delay for such tasks.