安卓开发——显示网速

相信大家在开发过程中经常需要为用户显示网速吧,不着急,咋们一步一步集成

1、计算网速函数
将该函数写到工具类里

    /**
 * 得到网络速度
 * @param context
 * @return
 */
    public static String  getNetSpeed(Context context) {


        String netSpeed = "0 kb/s";
        long nowTotalRxBytes = TrafficStats.getUidRxBytes(context.getApplicationInfo().uid)==TrafficStats.UNSUPPORTED ? 0 :(TrafficStats.getTotalRxBytes()/1024);//转为KB;
        long nowTimeStamp = System.currentTimeMillis();
        long speed = ((nowTotalRxBytes - lastTotalRxBytes) * 1000 / (nowTimeStamp - lastTimeStamp));//毫秒转换

        lastTimeStamp = nowTimeStamp;
        lastTotalRxBytes = nowTotalRxBytes;
        netSpeed  = String.valueOf(speed) + " kb/s";
        return  netSpeed;
    }
  • 1

2、
在textview中显示网速
在handler中刷新

                //展示网速
                case SHOW_SPEED:
                    //1、拿到网络速度
                    String netSpeed = CommonUtils.getNetSpeed(VideoPlayerActivity.this);
                    //2、设置TextView进行显示
                    mLlBufferTv.setText("玩命加载中..."+netSpeed);
                    //3、每两秒刷新一次
                    //这样写比较消耗性能,看视频我关注网速干毛啊,写到卡顿里
                    mHandler.removeMessages(SHOW_SPEED);
                    mHandler.sendEmptyMessageDelayed(SHOW_SPEED,2000);
                    break;
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
在Ubuntu 20.04中,你可以使用以下几种方法来实时显示网速: 1. 使用indicator-sysmonitor工具。你可以通过以下步骤来安装和使用它: 1) 添加indicator-sysmonitor的下载源:sudo add-apt-repository ppa:fossfreedom/indicator-sysmonitor -y 2) 更新apt-get:sudo apt-get update 3) 安装indicator-sysmonitor:sudo apt-get install indicator-sysmonitor 4) 启动indicator-sysmonitor:在终端中输入indicator-sysmonitor即可。 2. 使用Conky工具。你可以通过以下步骤来安装和使用它: 1) 安装Conky:sudo apt-get install conky-all 2) 创建一个Conky配置文件:在终端中输入nano ~/.conkyrc,然后将以下内容复制到文件中: alignment tr background yes border_width 1 cpu_avg_samples 2 default_color white default_outline_color white default_shade_color white draw_borders no draw_graph_borders yes draw_outline no draw_shades no use_xft yes xftfont DejaVu Sans:size=9 gap_x 5 gap_y 60 minimum_size 5 5 net_avg_samples 2 no_buffers yes override_utf8_locale yes double_buffer yes total_run_times 0 update_interval 1 uppercase no use_spacer yes show_graph_scale no show_graph_range no TEXT ${color white}${font DejaVu Sans:size=9}Up: ${upspeedf eth0} kB/s ${alignr} ${color white}${font DejaVu Sans:size=9}Down: ${downspeedf eth0} kB/s 3) 保存并退出文件。 4) 启动Conky:在终端中输入conky即可。 3. 使用System Monitor工具。你可以通过以下步骤来启动它: 1) 打开System Monitor:在Ubuntu 20.04的左侧菜单栏中搜索System Monitor并打开它。 2) 在System Monitor窗口中,选择“文件”菜单,然后选择“新建系统监视器”。 3) 在弹出的对话框中,选择要监视的资源(如网络),然后点击“添加”按钮。 4) 系统监视器窗口将显示所选资源的实时使用情况。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

苦茶子12138

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值