Android实时检测网络(流量监控)直接复制可用
效果如下
可搭配Android检测wifi信号强度,检测网络是否通畅 使用
创建工具类
import android.content.Context;
import android.net.TrafficStats;
import android.os.Handler;
import android.os.Message;
import java.util.Timer;
import java.util.TimerTask;
/**
* @ClassName: NetWorkListenerUtils
* @Description: 实时网络流量检测
* @Author: 有时有晌
* @Date: 2022/3/14 10:13
*/
public class NetWorkListenerUtils {
private Context context;
private Handler mHandler;
private long lastTotalRxBytes = 0;
private long lastTimeStamp = 0;
private Timer timer;
public NetWorkListenerUtils(Context context, Handler mHandler) {
this.context = context;
this.mHandler = mHandler;
}
public void startShowNetSpeed() {
lastTotalRxBytes = getTotalRxBytes();
lastTimeStamp = System.currentTimeMillis();
// 1s后启动任务,每2s执行一次、
if (timer == null) {
timer=new Timer();
}
timer.schedule(task, 1000, 1000);
}
public void unbindShowNetSpeed() {
if (timer != null) {
timer.cancel();
}
}
private long getTotalRxBytes() {
return TrafficStats.getUidRxBytes(context.getApplicationInfo().uid) == TrafficStats.UNSUPPORTED ? 0 : (TrafficStats.getTotalRxBytes() / 1024);//转为KB
}
private void showNetSpeed() {
long nowTotalRxBytes = getTotalRxBytes();
long nowTimeStamp = System.currentTimeMillis();
long speed = ((nowTotalRxBytes - lastTotalRxBytes) * 1000 / (nowTimeStamp - lastTimeStamp));//毫秒转换
long speed2 = ((nowTotalRxBytes - lastTotalRxBytes) * 1000 % (nowTimeStamp - lastTimeStamp));//毫秒转换
lastTimeStamp = nowTimeStamp;
lastTotalRxBytes = nowTotalRxBytes;
if (mHandler != null) {
Message msg = mHandler.obtainMessage();
msg.what = 100;
msg.obj = String.valueOf(speed) + "." + String.valueOf(speed2) + " kb/s";
mHandler.sendMessage(msg);//更新界面
}
}
TimerTask task = new TimerTask() {
@Override
public void run() {
showNetSpeed();
}
};
}
显示页面代码逻辑
创建对应的handler用于更新ui所展示的网速
private Handler mHnadler = new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 100:
tv_speed.setText("当前网速: " + msg.obj.toString());
break;
}
super.handleMessage(msg);
}
};
工具类调用
new NetWorkListenerUtils(this,mHnadler).startShowNetSpeed();
布局
<LinearLayout
android:id="@+id/ll_net_status"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="@+id/rl_setting"
android:layout_centerVertical="true"
android:orientation="horizontal"
android:gravity="center_vertical">
<ImageView
android:id="@+id/iv_net_status"
android:layout_width="@dimen/dimen_30dp"
android:layout_height="@dimen/dimen_30dp"
android:background="@drawable/wifi_success"
android:visibility="visible" />
<TextView
android:id="@+id/tv_speed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0kb/s"
android:textColor="@color/white"
android:visibility="gone"/>
</LinearLayout>
如上布局中主要用到的就是tv_speed这个TextView
注意:如使用请关注性能问题