I am working on an app which uploads a large amount of data. I want to determine the transfer rate of the upload, to show in a notification.
- One post suggests using the
WifiInfo
which will not work for mobile data. - Another post suggests getting the network type to estimate the speed.
I'm not satisfied with the answers in these posts, so I am asking again.
I've seen apps which display the upload transfer rate, as well as some custom ROMs like Resurrection Remix.
How can I determine the transfer rate of these uploads?
I am talking in the context of your app since this makes it easier to capture the real time speed of your uploaded data. You don't need any extra libraries or sdk api's.
You are presumably uploading the data in chunks to the server. So
a) You know the data size of each packet
b) You know the start time before sending the packet / before sending multiple packets
c) You know the end time of xy packets by the server response e.g. status 200
With that you have all parameters to calculate the upload speed
double uploadSpeed = packet.size / (endTime - startTime)
// time * 1000 to have it in secondsEDIT:
Since you are using
MultiPart
fromOkHttp
you can monitor the amount of bytes uploaded. Tracking progress of multipart file upload using OKHTTP. You would replacepacket.size
with the current uploaded amount and theendTime
would be an interval of xy seconds.It is feasible to obtain the transferred traffic amount using
android.net.TrafficStats
. Here is an implementation of this idea which measures the up-stream and down-stream transfer rate. You can measure the rate of mobile network by passingTrafficSpeedMeasurer.TrafficType.MOBILE
to theTrafficSpeedMeasurer
constructor, otherwise usingTrafficSpeedMeasurer.TrafficType.ALL
will result in measuring general traffic (WiFi/Mobile). Also by settingSHOW_SPEED_IN_BITS = true
inMainActivity
you can change the unit of speed measuring tobit
s per second.MainActivity.java
TrafficSpeedMeasurer.java
ITrafficSpeedListener.java
Utils.java
.
Visual Result
What you're trying to determine is the transfer rate of the bytes being uploaded over your HTTP Client. Obviously, this depends on the HTTP client you're using.
There's no out-of-the-box solution which applies to all HTTP clients used on Android. The Android SDK does not provide any methods for you to determine the transfer rate of a particular upload.
Fortunately, you're using OKHttp and there is a relatively straight-forward way to do this. You're going to have to implement a custom
RequestBody
, and observe the bytes being written to the buffer when the request is in flight.There's a 'recipe' for doing this on the OkHttp Github: https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/okhttp3/recipes/Progress.java
You could also refer to this StackOverflow question dealing with the exact same topic: Tracking progress of multipart file upload using OKHTTP
Another here: OKHTTP 3 Tracking Multipart upload progress