Showing posts with label Android code sample: WiFi. Show all posts
Showing posts with label Android code sample: WiFi. Show all posts

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.

Monday, December 21, 2015

Get HostName of WiFi hotspot clients, and check if it is still connected.


Previous posts show how to "Retrieve IP and MAC addresses from /proc/net/arp" and "Lookup manufacturer/vendor info from MAC address". This post show how to get the Host Name of the connected clients.

It can be noted that if we call getCanonicalHostName() or getHostName() methods of the InetAddressobjects, it will return  the IP address. If we call getLocalHost().getCanonicalHostName() or getLocalHost().getHostName() methods, it will return the host name, "localhost".

Also, if a devices disconnected, the file /proc/net/arp will not updated immediately. We can determine if it is still connected by calling inetAddress.isReachable(timeout). If false returned, means it is disconnected.

MainActivity.java
package com.blogspot.android_er.androidlistclient;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    Button btnRead;
    TextView textResult;

    ListView listViewNode;
    ArrayList<Node> listNote;
    ArrayAdapter<Node> adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnRead = (Button)findViewById(R.id.readclient);
        textResult = (TextView)findViewById(R.id.result);

        listViewNode = (ListView)findViewById(R.id.nodelist);
        listNote = new ArrayList<>();
        ArrayAdapter<Node> adapter =
                new ArrayAdapter<Node>(
                        MainActivity.this,
                        android.R.layout.simple_list_item_1,
                        listNote);
        listViewNode.setAdapter(adapter);

        btnRead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new TaskReadAddresses(listNote, listViewNode).execute();
            }
        });
    }

    class Node {
        String ip;
        String mac;
        String CanonicalHostName;
        String HostName;
        String LocalHostCanonicalHostName;
        String LocalHostHostName;
        String remark;
        boolean isReachable;

        Node(String ip, String mac){
            this.ip = ip;
            this.mac = mac;
            queryHost();
        }

        @Override
        public String toString() {
            return "IP: " + ip + "\n" +
                    "MAC: " + mac + "\n" +
                    "CanonicalHostName:\t" + CanonicalHostName + "\n" +
                    "HostName:\t" + HostName + "\n" +
                    "getLocalHost().getCanonicalHostName():\t" + LocalHostCanonicalHostName + "\n" +
                    "getLocalHost().getHostName():\t" + LocalHostHostName + "\n" +
                    "isReachable: " + isReachable +
                    "\n" + remark;
        }

        private void queryHost(){
            try {
                InetAddress inetAddress = InetAddress.getByName(ip);
                CanonicalHostName = inetAddress.getCanonicalHostName();
                HostName = inetAddress.getHostName();
                LocalHostCanonicalHostName = inetAddress.getLocalHost().getCanonicalHostName();
                LocalHostHostName = inetAddress.getLocalHost().getHostName();
                isReachable = inetAddress.isReachable(3000);

            } catch (UnknownHostException e) {
                e.printStackTrace();
                remark = e.getMessage();
            } catch (IOException e) {
                e.printStackTrace();
                remark = e.getMessage();
            }
        }
    }

    private class TaskReadAddresses extends AsyncTask<Void, Node, Void> {

        ArrayList<Node> array;
        ListView listView;

        TaskReadAddresses(ArrayList<Node> array, ListView v){
            listView = v;
            this.array = array;
            array.clear();
            textResult.setText("querying...");
        }

        @Override
        protected Void doInBackground(Void... params) {
            readAddresses();
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            textResult.setText("Done");
        }

        @Override
        protected void onProgressUpdate(Node... values) {
            listNote.add(values[0]);
            ((ArrayAdapter)(listView.getAdapter())).notifyDataSetChanged();
        }

        private void readAddresses() {
            BufferedReader bufferedReader = null;

            try {
                bufferedReader = new BufferedReader(new FileReader("/proc/net/arp"));

                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    String[] splitted = line.split(" +");
                    if (splitted != null && splitted.length >= 4) {
                        String ip = splitted[0];
                        String mac = splitted[3];
                        if (mac.matches("..:..:..:..:..:..")) {
                            Node thisNode = new Node(ip, mac);
                            publishProgress(thisNode);
                        }
                    }
                }

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally{
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}



Sunday, December 20, 2015

Lookup manufacturer info by MAC address, using www.macvendorlookup.com API

Last post show how to "Retrieve IP and MAC addresses of Android WiFi tethering clients from /proc/net/arp". This example show how to get vendor/manufacturer info of the associated MAC addresses.

(You can download runnable APK from link on bottom)


http://www.macvendorlookup.com/api provide API to lookup MAC Address Vendor/Manufacturer info.

Notice that this example haven't handle error condition.


MainActivity.java
package com.blogspot.android_er.androidlistclient;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    Button btnRead;
    TextView textResult;

    ListView listViewNode;
    ArrayList<Node> listNote;
    ArrayAdapter<Node> adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnRead = (Button)findViewById(R.id.readclient);
        textResult = (TextView)findViewById(R.id.result);

        listViewNode = (ListView)findViewById(R.id.nodelist);
        listNote = new ArrayList<>();
        ArrayAdapter<Node> adapter =
                new ArrayAdapter<Node>(
                        MainActivity.this,
                        android.R.layout.simple_list_item_1,
                        listNote);
        listViewNode.setAdapter(adapter);

        listViewNode.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Node node = (Node) parent.getAdapter().getItem(position);
                Toast.makeText(MainActivity.this,
                        "MAC:\t" + node.mac + "\n" +
                                "IP:\t" + node.ip + "\n" +
                                "company:\t" + node.company + "\n" +
                                "country:\t" + node.country + "\n" +
                                "addressL1:\t" + node.addressL1 + "\n" +
                                "addressL2:\t" + node.addressL2 + "\n" +
                                "addressL3:\t" + node.addressL3 + "\n" +
                                "type:\t" + node.type + "\n" +
                                "startHex:\t" + node.startHex + "\n" +
                                "endHex:\t" + node.endHex + "\n" +
                                "startDec:\t" + node.startDec + "\n" +
                                "endDec:\t" + node.endDec,
                        Toast.LENGTH_SHORT).show();
            }
        });

        btnRead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new TaskReadAddresses(listNote, listViewNode).execute();
            }
        });
    }



    class Node {
        String ip;
        String mac;

        String jsonBody;
        String startHex;
        String endHex;
        String startDec;
        String endDec;
        String company;
        String addressL1;
        String addressL2;
        String addressL3;
        String country;
        String type;

        String remark;

        String queryString = "http://www.macvendorlookup.com/api/v2/";

        Node(String ip, String mac){
            this.ip = ip;
            this.mac = mac;
            queryMacVendorLookup();
        }

        @Override
        public String toString() {
            return "IP: " + ip + "\n" + "MAC: " + mac + "\n" + company + "\n" + remark;
        }

        private String sendQuery(String qMac) throws IOException{
            String result = "";

            URL searchURL = new URL(queryString + qMac);

            HttpURLConnection httpURLConnection = (HttpURLConnection) searchURL.openConnection();

            if(httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK){
                InputStreamReader inputStreamReader = new InputStreamReader(httpURLConnection.getInputStream());
                BufferedReader bufferedReader = new BufferedReader(
                        inputStreamReader,
                        8192);

                String line = null;
                while((line = bufferedReader.readLine()) != null){
                    result += line;
                }

                bufferedReader.close();
            }

            return result;
        }


        private void ParseResult(String json){

            try {
                JSONArray jsonArray = new JSONArray(json);
                JSONObject jsonObject = (JSONObject) jsonArray.get(0);
                startHex = jsonObject.getString("startHex");
                endHex = jsonObject.getString("endHex");
                startDec = jsonObject.getString("startDec");
                endDec = jsonObject.getString("endDec");
                company = jsonObject.getString("company");
                addressL1 = jsonObject.getString("addressL1");
                addressL2 = jsonObject.getString("addressL2");
                addressL3 = jsonObject.getString("addressL3");
                country = jsonObject.getString("country");
                type = jsonObject.getString("type");
                remark = "OK";

            } catch (JSONException e) {
                e.printStackTrace();
                remark = e.getMessage();
            }

        }

        private void queryMacVendorLookup(){
            try {
                jsonBody = sendQuery(mac);
                ParseResult(jsonBody);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private class TaskReadAddresses extends AsyncTask<Void, Node, Void> {

        ArrayList<Node> array;
        ListView listView;

        TaskReadAddresses(ArrayList<Node> array, ListView v){
            listView = v;
            this.array = array;
            array.clear();
            textResult.setText("querying...");
        }

        @Override
        protected Void doInBackground(Void... params) {
            readAddresses();

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            textResult.setText("Done");
        }

        @Override
        protected void onProgressUpdate(Node... values) {
            listNote.add(values[0]);
            ((ArrayAdapter)(listView.getAdapter())).notifyDataSetChanged();

        }

        private void readAddresses() {

            BufferedReader bufferedReader = null;

            try {
                bufferedReader = new BufferedReader(new FileReader("/proc/net/arp"));

                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    String[] splitted = line.split(" +");
                    if (splitted != null && splitted.length >= 4) {
                        String ip = splitted[0];
                        String mac = splitted[3];
                        if (mac.matches("..:..:..:..:..:..")) {
                            Node thisNode = new Node(ip, mac);
                            publishProgress(thisNode);
                        }
                    }
                }

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally{
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}


layout/activity_main.xml
<?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.androidlistclient.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" />

    <Button
        android:id="@+id/readclient"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAllCaps="false"
        android:text="Read Ip/MAC addresses"/>

    <TextView
        android:id="@+id/result"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <ListView
        android:id="@+id/nodelist"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
</LinearLayout>


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

download filesDownload runnable APK .

Next:
Get HostName of WiFi hotspot clients, and check if it is still connected.

Friday, March 20, 2015

Get WiFi info using WifiManager and WifiInfo

Example to get connected WiFi information using WifiManager and WifiInfo.


package com.example.androidwifisetting;

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

/*
 * Permission needed:
 * android.permission.ACCESS_WIFI_STATE
 * 
 * minSdkVersion="21"
 * for WifiInfo.getFrequency()
 */

public class MainActivity extends ActionBarActivity {
 
 TextView textWifiInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textWifiInfo = (TextView)findViewById(R.id.wifiinfo);
        
        String strWifiInfo = "";

        WifiManager wifiManager = (WifiManager)getSystemService(Context.WIFI_SERVICE);
        WifiInfo connectionInfo = wifiManager.getConnectionInfo();

        int ipAddress = connectionInfo.getIpAddress();
        String ipString = String.format("%d.%d.%d.%d",
          (ipAddress & 0xff),
          (ipAddress >> 8 & 0xff),
          (ipAddress >> 16 & 0xff),
          (ipAddress >> 24 & 0xff));
        
        final int NumOfRSSILevels = 5;
        
        strWifiInfo += 
         "SSID: " + connectionInfo.getSSID() + "\n" +
         "BSSID: " + connectionInfo.getBSSID() + "\n" +
         "IP Address: " + ipString + "\n" +
         "MAC Address: " + connectionInfo.getMacAddress() + "\n" +
         "Frequency: " + connectionInfo.getFrequency() + WifiInfo.FREQUENCY_UNITS + "\n" +
         "LinkSpeed: " + connectionInfo.getLinkSpeed() + WifiInfo.LINK_SPEED_UNITS + "\n" +
         "Rssi: " + connectionInfo.getRssi() + "dBm" + "\n" +
         "Rssi Level: " + 
          WifiManager.calculateSignalLevel(connectionInfo.getRssi(), NumOfRSSILevels) + 
          " of " + NumOfRSSILevels;

        textWifiInfo.setText(strWifiInfo);
    }

}

<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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context="com.example.androidwifisetting.MainActivity" >

    <TextView
        android:id="@+id/title"
        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/wifiinfo"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="20dp"
        android:textStyle="bold" />

</LinearLayout>