Quite a lot differs!
Using AsyncTask
for HTTP requests is pretty much one of the worst things you can do on Android. It's fraught with problems and gotchas that are best unconditionally avoided. For example, you cannot cancel a request during execution. The patterns of using AsyncTask
also commonly leak a reference to an Activity
, a cardinal sin of Android development.
OkHttp's async is vastly superior for many reasons:
- It supports native canceling. If a request is in-flight, the reference to the
Callback
is freed and will never be called. Additionally, if the request has not started yet it never will be executed. If you are using HTTP/2 or SPDY we can actually cancel mid-request saving bandwidth and power.
- It supports tagging multiple requests and canceling them all with a single method call. This means every request you make in, say, an
Activity
can be tagged with the Activity
instance. Then in onPause
or onStop
you can cancel all requests tagged with the Activity
instance.
- If you are using HTTP/2 or SPDY requests and responses are multiplexed over a single connection to the remote server and by using the asynchronous
Call
mechanism this is much more efficient than the blocking version.
So if you can, use Call.enqueue
!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…