Monday, January 18, 2016

Get WiFi link speed and frequency

Example show how to get WiFi link speed and frequency:


When WiFi OFF


package com.blogspot.android_er.androidwifispeedfrequency;

import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

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

        TextView textInfo = (TextView)findViewById(R.id.info);
        TextView textSpeed = (TextView)findViewById(R.id.speed);
        TextView textFreq = (TextView)findViewById(R.id.frequency);

        WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        if(wifiManager!=null){
            textInfo.setText(wifiManager.toString());
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            textSpeed.setText("Link Speed: " + wifiInfo.getLinkSpeed() + wifiInfo.LINK_SPEED_UNITS);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                textFreq.setText("Freuency: " + wifiInfo.getFrequency() + wifiInfo.FREQUENCY_UNITS);
            }
        }else{
            textInfo.setText("wifiManager == null!");
        }
    }
}


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    android:orientation="vertical"
    tools:context="com.blogspot.android_er.androidwifispeedfrequency.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:autoLink="web"
        android:text="http://android-er.blogspot.com/"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/info"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textStyle="italic"/>
    <TextView
        android:id="@+id/speed"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textStyle="bold"
        android:textSize="30dp"/>
    <TextView
        android:id="@+id/frequency"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textStyle="bold"
        android:textSize="30dp"/>

</LinearLayout>



uses-permission of "android.permission.ACCESS_WIFI_STATE" is needed in AndroidManifest.xml.

1 comment:

Unknown said...

The getFrequency method only works on devices with Api 21 or higher i.e. lollipop. How do we get frequency in lower versions like KitKat?