I need todo some operations in my android app based on the upload speed. It is an broadcasting app, based on network upload speed I want update the resolution and bitrate. For example if the upload speed is below 0.5 Mb I want to set different bitrate and resolution as 360p. How to measure upload speed?
I tried with Connectivity Manager but it gives only the overall strength. But not the exact speed.
I used the following for checking download/upload speed every 5 seconds.
import android.net.TrafficStats
object RetrieveData {
private var totalDownload: Long = 0
private var totalDownload_n: Long = 0
private var totalUpload: Long = 0
private var totalUpload_n: Long = 0
fun findData(uid: Int): List<Long?> {
val allData: MutableList<Long?> = ArrayList<Long?>()
if (totalDownload == 0L) {
totalDownload = TrafficStats.getUidRxBytes(uid)
}
if (totalUpload == 0L) {
totalUpload = TrafficStats.getUidTxBytes(uid)
}
val newTotalDownload = TrafficStats.getUidRxBytes(uid)
val incDownload = newTotalDownload - totalDownload
val newTotalUpload = TrafficStats.getUidTxBytes(uid)
val incUpload = newTotalUpload - totalUpload
totalDownload = newTotalDownload
totalUpload = newTotalUpload
allData.add(incDownload)
allData.add(incUpload)
return allData
}
and
val timer=fixedRateTimer("ss",false,1000,5000){
getData()
}
and
fun getData() {
val allData = findData(applicationInfo.uid)
val mDownload = allData[0]
val mUpload = allData[1]
val df = DecimalFormat("#.##")
var downloadSpeedApi=0
var uploadSpeedApi=0
var upSpeed: String = if (mUpload!! < 128) {
mUpload.toInt().toString() + " B/s"
} else if (mUpload < 1048576) {
(mUpload.toInt() / 1024).toString() + " KB/s"
} else {
df.format(mUpload.toDouble() / 1048576.0).toString() + " MB/s"
}
var downSpeed: String = if (mDownload!! < 128) {
mDownload.toInt().toString() + " B/s"
} else if (mDownload < 1048576) {
(mDownload.toInt() / 1024).toString() + " KB/s"
} else {
df.format(mDownload.toDouble() / 1048576.0).toString() + " MB/s"
}
Log.d("MyTAG", "$downSpeed, $upSpeed")