在开发中,有时候常常需要根据用户当前的网速来做一些操作,比如图片的加载,当网速非常好的时候,比如连接的是wifi,我们就会下载高分辨率的图片,反之,当用户使用的是2g网时,我们则给他下载低分辨率的小图,从而节省用户流量。
而Facebook其实已经给我们提供了这么一个库,详见network-connection-class。
使用其实超级简单,先加入依赖
compile ‘com.facebook.network.connectionclass:connectionclass:1.0.1‘
在该库中,我们使用的主要是ConnectionClassManager这个类,这个类中有几个主要的方法。
- getCurrentBandwidthQuality() 获得当前网速的质量,是一个枚举类型。
public enum ConnectionQuality {
/**
* Bandwidth under 150 kbps.
*/
POOR,
/**
* Bandwidth between 150 and 550 kbps.
*/
MODERATE,
/**
* Bandwidth between 550 and 2000 kbps.
*/
GOOD,
/**
* EXCELLENT - Bandwidth over 2000 kbps.
*/
EXCELLENT,
/**
* Placeholder for unknown bandwidth. This is the initial value and will stay at this value
* if a bandwidth cannot be accurately found.
*/
UNKNOWN
}
- getDownloadKBitsPerSecond() 获得每秒的下载速度
此外,我们可以获得网络质量发生改变时的通知,比如从POOR变成了GOOD,我们只要注册监听器即可,这是一个观察者模式。
private ConnectionChangedListener listener = new ConnectionChangedListener();
private class ConnectionChangedListener implements
ConnectionClassManager.ConnectionClassStateChangeListener {
@Override
public void onBandwidthStateChange(ConnectionQuality bandwidthState) {
Log.e("onBandwidthStateChange", bandwidthState.toString());
}
}
我们在Activity的onResume中注册监听器,在onPause中取消注册
@Override
protected void onResume() {
super.onResume();
ConnectionClassManager.getInstance().register(listener);
}
@Override
protected void onPause() {
super.onPause();
ConnectionClassManager.getInstance().remove(listener);
}
之后,在网络请求之前,我们需要调用开始采样的方法
DeviceBandwidthSampler.getInstance().startSampling();
网络请求完成后,结束采样
DeviceBandwidthSampler.getInstance().stopSampling();
假设我们使用的是OkHttp
OkHttpClient client = new OkHttpClient();
Request.Builder builder = new Request.Builder();
Request request = builder.url("http://www.baidu.com").build();
DeviceBandwidthSampler.getInstance().startSampling();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
DeviceBandwidthSampler.getInstance().stopSampling();
Log.e("TAG","onFailure:"+e);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
DeviceBandwidthSampler.getInstance().stopSampling();
Log.e("TAG","onResponse:"+response);
final ConnectionQuality connectionQuality = ConnectionClassManager.getInstance().getCurrentBandwidthQuality();
final double downloadKBitsPerSecond = ConnectionClassManager.getInstance().getDownloadKBitsPerSecond();
Log.e("TAG","connectionQuality:"+connectionQuality+" downloadKBitsPerSecond:"+downloadKBitsPerSecond+" kb/s");
tv.post(new Runnable() {
@Override
public void run() {
tv.setText("connectionQuality:"+connectionQuality+"\n"+"downloadKBitsPerSecond:"+downloadKBitsPerSecond+" kb/s");
}
});
}
});
最终的效果如下图所示
但是该库只能获得下载速度,上传的速度无法获得,使用的时候注意一下即可。
源码下载
http://download.csdn.net/detail/sbsujjbcy/9438965
时间: 2024-10-19 17:06:23