安卓测试网速代码
时间: 2023-07-09 13:20:21 浏览: 75
可以使用 Android 自带的 NetworkStatsManager 类来获取网络使用情况和网速。以下是一个简单的代码示例:
```java
private NetworkStatsManager networkStatsManager;
private int uid;
// 初始化 NetworkStatsManager 和 uid
networkStatsManager = (NetworkStatsManager) getSystemService(Context.NETWORK_STATS_SERVICE);
uid = getApplicationInfo().uid;
// 获取当前应用的网速
long rxBytes = getRxBytesMobile() + getRxBytesWifi();
long txBytes = getTxBytesMobile() + getTxBytesWifi();
long totalBytes = rxBytes + txBytes;
// 获取移动网络接收字节数
private long getRxBytesMobile() {
NetworkStats.Bucket bucket = null;
try {
bucket = networkStatsManager.querySummaryForDevice(ConnectivityManager.TYPE_MOBILE,
getSubscriberId(), 0, System.currentTimeMillis());
} catch (RemoteException e) {
e.printStackTrace();
}
return bucket == null ? 0 : bucket.getRxBytes();
}
// 获取移动网络发送字节数
private long getTxBytesMobile() {
NetworkStats.Bucket bucket = null;
try {
bucket = networkStatsManager.querySummaryForDevice(ConnectivityManager.TYPE_MOBILE,
getSubscriberId(), 0, System.currentTimeMillis());
} catch (RemoteException e) {
e.printStackTrace();
}
return bucket == null ? 0 : bucket.getTxBytes();
}
// 获取 WiFi 接收字节数
private long getRxBytesWifi() {
NetworkStats.Bucket bucket = null;
try {
bucket = networkStatsManager.querySummaryForDevice(ConnectivityManager.TYPE_WIFI,
"", 0, System.currentTimeMillis());
} catch (RemoteException e) {
e.printStackTrace();
}
return bucket == null ? 0 : bucket.getRxBytes();
}
// 获取 WiFi 发送字节数
private long getTxBytesWifi() {
NetworkStats.Bucket bucket = null;
try {
bucket = networkStatsManager.querySummaryForDevice(ConnectivityManager.TYPE_WIFI,
"", 0, System.currentTimeMillis());
} catch (RemoteException e) {
e.printStackTrace();
}
return bucket == null ? 0 : bucket.getTxBytes();
}
// 获取当前 SIM 卡的 IMSI 号
private String getSubscriberId() {
TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
return tm.getSubscriberId();
}
```
这个代码可以同时获取移动网络和 WiFi 网络的网速,单位是字节。你可以将获取的字节数转换为比特数或者千字节/秒。