Tôi đã sử dụng một thiết lập nhỏ để kiểm tra băng thông để xác định cách chia tỷ lệ mọi thứ, chẳng hạn như hình ảnh.
Dưới hoạt động, trong AndroidManifest:
<intent-filter>
...
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
</intent-filter>
Trong hoạt động nơi kiểm tra đang được thực hiện:
boolean network;
int bandwidth;
@Override
public void onCreate(Bundle savedInstanceState) {
...
network = isDataConnected();
bandwidth = isHighBandwidth();
registerReceiver(new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
network = isDataConnected();
bandwidth = isHighBandwidth();
}
}, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"));
...
}
...
private boolean isDataConnected() {
try {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo().isConnectedOrConnecting();
} catch (Exception e) {
return false;
}
}
private int isHighBandwidth() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info.getType() == ConnectivityManager.TYPE_WIFI) {
WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
return wm.getConnectionInfo().getLinkSpeed();
} else if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
return tm.getNetworkType();
}
return 0;
}
Một cách sử dụng ví dụ sau đó sẽ là:
if (network) {
if (bandwidth > 16) {
// Code for large items
} else if (bandwidth <= 16 && bandwidth > 8) {
// Code for medium items
} else {
//Code for small items
}
} else {
//Code for disconnected
}
Đó là không phải là đẹp nhất, nhưng nó cho phép đủ linh hoạt mà tôi có thể thay đổi băng thông cắt cho các hạng mục de đang chờ xử lý những gì họ đang có và yêu cầu của tôi đối với họ.
hey Cảm ơn nó đã hoạt động như mong đợi – Sam97305421562
như @noillusioin nói, activeNetInfo có thể rỗng. Đây là dấu hiệu cho thấy kết nối mạng JUST DISCONNECTED nếu bạn biết (lưu trạng thái) mà bạn đã kết nối trước đó. – larham1
Bạn cũng cần kiểm tra NetworkInfo.isConnected – shuriquen