Home > Blockchain >  how do I make a http request in view?
how do I make a http request in view?

Time:12-19

Can I start a http request in View's onAttachedToWindow() Method, and cancel request in onDetachedFromWindow() Method?

class TestView(context: Context) : View(context) {
var call: Call? = null

override fun onAttachedToWindow() {
    super.onAttachedToWindow()
    call = OkHttpClient().newCall(Request.Builder().build())
    call?.enqueue(object : Callback {})
    call?.cancel()
}

override fun onDetachedFromWindow() {
    call?.cancel()
    super.onDetachedFromWindow()
}

}

CodePudding user response:

Yes, you can start a HTTP request in the onAttachedToWindow() method and cancel the request in the onDetachedFromWindow() method as shown in your code.

The onAttachedToWindow() method is called when a view is attached to a window, which means it has a valid surface for drawing. In this method, you can initiate any actions that should be performed when the view becomes visible on the screen.

The onDetachedFromWindow() method is called when a view is detached from a window. This can happen when the view is removed from the window or when the window is destroyed. In this method, you can cancel any ongoing actions or release any resources that are no longer needed.

In your code, you are using the OkHttp library to create a new call and enqueue it. When the view is detached from the window, you are canceling the call using the cancel() method. This will stop the call from being executed and free up any resources being used by the call.

It's important to note that the onDetachedFromWindow() method may not be called immediately when the view is removed from the window. There may be a delay between the view being removed and the method being called, so you should not rely on this method for time-critical tasks.

  • Related