最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Android?獲取實(shí)時(shí)網(wǎng)速實(shí)現(xiàn)詳解

 更新時(shí)間:2022年11月27日 16:08:22   作者:ChenYhong  
這篇文章主要為大家介紹了Android?獲取實(shí)時(shí)網(wǎng)速實(shí)現(xiàn)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪

正文

最近接到個(gè)需求,需要計(jì)算WebView加載網(wǎng)頁時(shí)的網(wǎng)速。查詢了一下,Android沒有提供直接獲取網(wǎng)速的Api,但是提供了獲取流量的類TrafficStats。本文介紹如何使用Trafficstats來實(shí)現(xiàn)獲取網(wǎng)速功能。

TrafficStats簡介

TrafficStats提供了一些獲取設(shè)備從本次開機(jī)到目前為止傳輸/接收的流量的接口,如下:

方法參數(shù)說明
getTotalTxBytes-獲取設(shè)備本次開機(jī)到目前為止,WI-FI、流量下傳輸?shù)淖止?jié)總數(shù)。
getTotalRxBytes-獲取設(shè)備本次開機(jī)到目前為止,WI-FI、流量下接收的字節(jié)總數(shù)。
getMobileTxBytes-獲取設(shè)備本次開機(jī)到目前為止,流量下傳輸?shù)淖止?jié)總數(shù)。
getMobileRxBytes-獲取設(shè)備本次開機(jī)到目前為止,流量下接收的字節(jié)總數(shù)。
getUidTxBytesuid獲取應(yīng)用從本次開機(jī)到目前為止,WI-FI、流量下傳輸?shù)淖止?jié)總數(shù)。
getUidRxBytesuid獲取應(yīng)用從本次開機(jī)到目前為止,WI-FI、流量下接收的字節(jié)總數(shù)。

上述接口可以滿足實(shí)現(xiàn)計(jì)算網(wǎng)速的需求,TrafficStats類其他接口可以查看官方文檔

實(shí)現(xiàn)獲取網(wǎng)速

可以通過一段時(shí)間內(nèi)傳輸?shù)牧髁砍r(shí)間計(jì)算出上行網(wǎng)速,通過一段時(shí)間內(nèi)接收的流量除去時(shí)間計(jì)算出下行網(wǎng)速。

TrafficStats類的接口獲取的網(wǎng)速是從開機(jī)時(shí)就開始計(jì)算的,因此,要計(jì)算一段時(shí)間內(nèi)的流量需要在開始時(shí)獲取一次流量數(shù)據(jù),結(jié)束時(shí)獲取一次流量數(shù)據(jù),相減得出一段時(shí)間的實(shí)際流量。

實(shí)時(shí)網(wǎng)速

本文用getUidTxBytesgetUidRxBytes來演示,其他方法也是類似的,如下:

object NetSpeedUtils {
    var netSpeedCallback: NetSpeedCallback? = null
    private var timer: Timer? = null
    private var timerTask: TimerTask? = null
    private var lastTotalReceiveBytes: Long = 0
    private var lastTotalTransferBytes: Long = 0
    /**
     * 根據(jù)應(yīng)用uid獲取設(shè)備啟動(dòng)以來,該應(yīng)用接收到的總字節(jié)數(shù)
     *
     * @param uid 應(yīng)用的uid
     */
    fun getTotalReceiveBytes(): Long {
        var receiveBytes: Long = TrafficStats.UNSUPPORTED.toLong()
        ExampleApplication.exampleContext?.run {
            receiveBytes = TrafficStats.getUidRxBytes(applicationInfo.uid)
        }
        // 當(dāng)獲取不到時(shí),會(huì)返回TrafficStats.UNSUPPORTED
        return if (receiveBytes == TrafficStats.UNSUPPORTED.toLong()) 0 else receiveBytes / 1024
    }
    /**
     * 根據(jù)應(yīng)用uid獲取設(shè)備啟動(dòng)以來,該應(yīng)用傳輸?shù)目傋止?jié)數(shù)
     *
     * @param uid 應(yīng)用的uid
     */
    fun getTotalTransferBytes(): Long {
        var transferBytes: Long = TrafficStats.UNSUPPORTED.toLong()
        ExampleApplication.exampleContext?.run {
            transferBytes = TrafficStats.getUidTxBytes(applicationInfo.uid)
        }
        // 當(dāng)獲取不到時(shí),會(huì)返回TrafficStats.UNSUPPORTED
        return if (transferBytes == TrafficStats.UNSUPPORTED.toLong()) 0 else transferBytes / 1024
    }
    // 通過Timer每隔1秒計(jì)算網(wǎng)速
    private fun calculateNetSpeed() {
        ExampleApplication.exampleContext?.run {
            val nowTotalReceiveBytes = getTotalReceiveBytes()
            val nowTotalTransferBytes = getTotalTransferBytes()
            val downloadSpeed = nowTotalReceiveBytes - lastTotalReceiveBytes
            val uploadSpeed = nowTotalTransferBytes - lastTotalTransferBytes
            lastTotalReceiveBytes = nowTotalReceiveBytes
            lastTotalTransferBytes = nowTotalTransferBytes
            netSpeedCallback?.onNetSpeedChange("$downloadSpeed kb/s", "$uploadSpeed kb/s")
        }
    }
    fun startMeasuringNetSpeed() {
        if (timer == null && timerTask == null) {
            timer = Timer()
            timerTask = object : TimerTask() {
                override fun run() {
                    calculateNetSpeed()
                }
            }
            timer?.run { timerTask?.let { schedule(it, 0L, 1000L) } }
        }
    }
    fun stopMeasuringNetSpeed() {
        timerTask?.cancel()
        timerTask = null
        timer?.cancel()
        timer = null
    }
    interface NetSpeedCallback {
        fun onNetSpeedChange(downloadSpeed: String, uploadSpeed: String)
    }
}
// 示例類
class TrafficStatsActivity : BaseGestureDetectorActivity() {
    private lateinit var binding: LayoutTrafficStatsActivityBinding
    @SuppressLint("SetTextI18n")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this, R.layout.layout_traffic_stats_activity)
        binding.includeTitle.tvTitle.text = "TrafficStatsExample"
        NetSpeedUtils.netSpeedCallback = object : NetSpeedUtils.NetSpeedCallback {
            override fun onNetSpeedChange(downloadSpeed: String, uploadSpeed: String) {
                binding.tvNetSpeed.run { post { text = "downloadSpeed:$downloadSpeed , uploadSpeed:$uploadSpeed" } }
            }
        }
        binding.btnStartMeasureNetSpeed.setOnClickListener {
            NetSpeedUtils.startMeasuringNetSpeed()
        }
        binding.btnStopMeasureNetSpeed.setOnClickListener {
            NetSpeedUtils.stopMeasuringNetSpeed()
        }
        initWebViewSetting(binding.webView)
        binding.webView.loadUrl("https://go.minigame.vip/")
    }
    @SuppressLint("JavascriptInterface", "SetJavaScriptEnabled")
    private fun initWebViewSetting(webView: WebView?) {
        webView?.run {
            settings.cacheMode = WebSettings.LOAD_DEFAULT
            settings.domStorageEnabled = true
            settings.allowContentAccess = true
            settings.allowFileAccess = true
            settings.useWideViewPort = true
            settings.loadWithOverviewMode = true
            settings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
            settings.javaScriptEnabled = true
            settings.javaScriptCanOpenWindowsAutomatically = true
            settings.setSupportMultipleWindows(true)
        }
    }
    override fun onDestroy() {
        super.onDestroy()
        binding.webView.clearHistory()
        binding.webView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null)
        binding.root.run {
            if (this is ViewGroup) {
                this.removeView(binding.webView)
            }
        }
        binding.webView.destroy()
    }
}

效果如圖:

以上就是Android 獲取實(shí)時(shí)網(wǎng)速實(shí)現(xiàn)詳解的詳細(xì)內(nèi)容,更多關(guān)于Android 獲取實(shí)時(shí)網(wǎng)速的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評(píng)論

嘉鱼县| 泾源县| 会同县| 宿松县| 常山县| 新余市| 西畴县| 肇庆市| 诸城市| 吉木萨尔县| 文成县| 伊宁市| 项城市| 阿鲁科尔沁旗| 佳木斯市| 泰州市| 东兰县| 平阳县| 铜鼓县| 张家界市| 长垣县| 五指山市| 太原市| 江城| 龙泉市| 洛阳市| 晋城| 张家港市| 海盐县| 新营市| 六盘水市| 瑞丽市| 马龙县| 沁阳市| 武乡县| 永善县| 乌拉特后旗| 来安县| 岑巩县| 无棣县| 怀安县|