Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách lấy tốc độ liên kết Wi-Fi hiện tại trên Android

Giới thiệu

Sử dụng WifiInfo.getLinkSpeed() để lấy tốc độ lý thuyết (Mbps) của kết nối Wi-Fi hiện tại.

Code (MainActivity.java)

public class MainActivity extends AppCompatActivity {

    private TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = findViewById(R.id.text);

        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();

        if (wifiInfo != null) {
            int speedMbps = wifiInfo.getLinkSpeed(); // đơn vị Mbps
            textView.setText("Tốc độ liên kết: " + speedMbps + " Mbps");
        } else {
            textView.setText("Chưa kết nối Wi-Fi");
        }
    }
}

Quyền cần thiết

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

Giải thích

  • getLinkSpeed() trả về tốc độ PHY (physical layer) theo đơn vị Mbps, ví dụ: 72, 144, 300, 866...
  • Đây là tốc độ tối đa lý thuyết của chuẩn Wi-Fi (802.11n, ac, ax...), không phải tốc độ thực tế (thường thấp hơn do nhiễu, khoảng cách).
  • Để đo tốc độ thực, cần test download/upload file hoặc dùng Speedtest API.