Quantcast
Channel: Yudiz Solutions Ltd.
Viewing all articles
Browse latest Browse all 595

Communication over WiFi In Android

$
0
0

What is WiFi?

WiFI or Wireless Fidelity is a technology that allows computers, smartphones or other devices to connect to the Internet or communicate with each other wirelessly within a particular area.Many facilities are provided by WiFi and hotspot is one of them.

What is Hotspot?

A hotspot is a wireless network(WLAN) that provides Internet connection and virtual private network access from particular location. For e.g. Employee connect their own company network remotely with a secure connection or group of people connected to one network for playing game,chat etc

Hotspot in Mobile Device

Mobile hotspots (portable hotspot) are portable devices or features on smartphones that provide wireless Internet access on many devices (like laptop, smartphone, tablet, portable gaming device, etc.)

Wireless chat application using portable WiFi hotspot

The Android platform provides support for the wireless network, which allows a device to wirelessly connect with other device and exchange data between them. The application framework provide wireless APIs for accessing wireless functionality. These APIs help for connecting devices wirelessly to each other, like point-to-point and point-to-multipoint communications.

This application allows two or more Android devices to communicate with each other without using any resources (like Internet ,chat servers). For communication between them we need tethering or hotspot.

Purpose of this application is making wireless communication between android devices. We need minimum two device for communication. One device enables tethering(via wifi). So we called is server and another device connect via wifi so we called client. If you want to connect more than two device. It is possible and it become group chat. To open a connection between devices, you need to make tcp/ip connection using a Socket and ServerSocket in Java.These Class are provided by java. If you want to use library for simplify coding then you can use it.

A socket is a software endpoint that establishes communication between connected nodes.

It can be two or more node(device). But primary stage one device is server that created socket which contain port for running services and ip address for connection purpose,and another device is client which connect to server.

Code Snippet and Requirements:

1) Android 2.2 or higher version(hotspot required)

2) Application Permission Require :

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

3) Create Hotspot:

// this method help to create hotspot programmatically   
        public static boolean setHotSpot(String SSID, String passWord) {   
       Method[] mMethods = wifiManager.getClass().getDeclaredMethods();

   for (Method mMethod : mMethods) {

           if (mMethod.getName().equals("setWifiApEnabled")) {
               WifiConfiguration wifiConfig = new WifiConfiguration();
               if (passWord == "") {
                   wifiConfig.SSID = SSID;
                    wifiConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
                    wifiConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
                          wifiConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
                wifiConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
                       } else {
                   wifiConfig.SSID = SSID;
                   wifiConfig.preSharedKey = passWord;
                   wifiConfig.hiddenSSID = true;
                      wifiConfig.status = WifiConfiguration.Status.ENABLED;
                   wifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
                   wifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
                   wifiConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
                   wifiConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
                  wifiConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
                   wifiConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
                   wifiConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
                      }
                   try {
                       mMethod.invoke(wifiManager, netConfig, true);
                  wifiManager.saveConfiguration();
                       return true;

                      } catch (Exception e) {

                       }
                }
               return false;
                }

4) Join Hotspot

// this method help to connect hotspot programmatically 
          public static boolean connectToHotspot(String netSSID, String netPass) {
       WifiConfiguration wifiConf = new WifiConfiguration();
      List scanResultList = wifiManager.getScanResults();
       if (wifiManager.isWifiEnabled()) {
                  for (ScanResult result : scanResultList) {
                  if (result.SSID.equals(netSSID)) {

                       removeWifiNetwork(result.SSID, wifiManager);
                        String mode = getSecurityMode(result);// get mode of hospot

                          if (mode.equalsIgnoreCase("OPEN")) {
        wifiConf.SSID = "\"" + netSSID + "\"";
                                wifiConf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
                                int res = wifiManager.addNetwork(wifiConf);
                                wifiManager.disconnect();
                              wifiManager.enableNetwork(res, true);
                            wifiManager.reconnect();
                         wifiManager.setWifiEnabled(true);
                       return true;
                   } else if (mode.equalsIgnoreCase("WEP")) {
                                wifiConf.SSID = "\"" + netSSID + "\"";
                              wifiConf.wepKeys[0] = "\"" + netPass + "\"";
                        wifiConf.wepTxKeyIndex = 0;
                           wifiConf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
                              wifiConf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
                                int res = wifiManager.addNetwork(wifiConf);
                           wifiManager.disconnect();
                               wifiManager.enableNetwork(res, true);
                               wifiManager.reconnect();
                               wifiManager.setWifiEnabled(true);
 return true;
} else {
                             wifiConf.SSID = "\"" + netSSID + "\"";
                           wifiConf.preSharedKey = "\"" + netPass + "\"";
                            wifiConf.hiddenSSID = true;
                             wifiConf.status = WifiConfiguration.Status.ENABLED;
                           wifiConf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
                          wifiConf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
                          wifiConf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
                         wifiConf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
                           wifiConf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
                           wifiConf.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
                           wifiConf.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
                           int res = wifiManager.addNetwork(wifiConf);
                          wifiManager.disconnect();
                          wifiManager.enableNetwork(res, true);
                          wifiManager.reconnect();
                          wifiManager.saveConfiguration();
                          wifiManager.setWifiEnabled(true);
                     return true;
                    }
                  }
                }
              }
             return false;
         }
// get Security Mode
public static String getSecurityMode(ScanResult scanResult) {
   final String cap = scanResult.capabilities;
   final String[] modes = {"WPA", "EAP", "WEP"};
   for (int i = modes.length - 1; i >= 0; i--) {
               if (cap.contains(modes[i])) {
                       return modes[i];
               }
    }
   return "OPEN";
  }

5) Socket

i)Socket Class
Socket
ServerSocket
DatagramSocket
MulticastSocket(Required for multicast or group communication)

ii)Server Socket
The ServerSocket provide a listening TCP connection. Once a connection is requested, the ServerSocket object will return as Socket object representing the connection.

Constructors:
The ServerSocket provides four constructors. Empty construction means port number assigned by OS. With one argument port number take as argument to listen for connection requests. A constructor is provided facility of maximum time to wait for a connection as a second argument.And at last InetAdress or IP Address take as last argument.

Methods:
The most important method is accept(). It returns a Socket that is connected to the client. The close() method give idea of whether operating system to stop listening for requests on the socket.Some methods available for retrieve the hostname, port number etc.

//port number range 1024-65535
            public static final int PORT = 2024;

//Server Socket declaration 
         ServerSocket serversocket = null;
             Socket socket = null;
             System.out.println(" Waiting !! ");

try
         {
          //  Initialising the ServerSocket with input as port number
          serversocket =  new ServerSocket(PORT);

          try
          {

               // makes a socket connection for clients 
              // accept method waiting for connection(listening mode)
          socket = serversocket.accept();

          // Receive message from client
          DataInputStream dis = new                 
                DataInputStream(socket.getInputStream());

// for reading dis.readLine();

     // Send message to the client 

DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
dos.writeUTF(“Hello User);
 dos.close();

    // Close the Socket connection 
                socket.close();
  }
           catch(SocketException socketexception)
        {
                System.out.println("Server problem  "+socketexception.getMessage());
           }
        catch(Exception exception)
        {    
System.out.println("Something wrong error occure” + exception.getMessage()) ;     
 }               

 //get address of socket
         System.out.println(" Connection from :  " +  socket.getInetAddress());

iii) Client  Socket(Socket)

Socket Class provides a TCP connection. When a socket is created, a connection is opened to the specified destination, it can be domain name or ip address with specific port number.

Constructors:

The Socket provides the programmer with multiple constructors.

Empty socket is system default socket with the system-default type of SocketImpl. Another two constructors is Proxy and SocketImpl as single argument. Main focus is InetAddress constructor which may be specified as a string or an InetAddress, and the port number on the host to connect to. In each case, connection type is described as connectionless or not as set false for connectionless.

Methods:

Socket provides two methods are getInputStream() and getOutputStream(), which give return type as  stream objects, which help to communicate through the socket. Object provided virtual link to the socket.The close() method give idea of whether operating system to stop listening for requests on the socket.Some methods available for retrieve information about the connection to the local host and remote port numbers and an integers representing the remote host.

// Declaration

Server.PORT=2024;

Socket socket=null;
System.out.println(" Trying to connecting server");
try
{
// to get the ip address of the  server by the name
//first way

InetAddress ip =InetAddress.getByName (“yudiz.com");

// default or second way if hotspot created by server then 192.168.43.1 (fixed)
// Connecting to the port 2024 declared in the Server class
// Creates a socket with the server bind to it.

socket= new Socket(ip,Server.PORT);

// Receive message from server

DataInputStream dis = new
DataInputStream(socket.getInputStream());
System.out.println(dis.readLine());

//output : Hello User

// Send message to the server

DataOutputStream dos = new

DataOutputStream(socket.getOutputStream());

dos.writeUTF(“Hello Server);

dos.close();
}
catch(SocketException socketexception)
{    System.out.println("Socket Exception”);
}
catch(IOException exception)
{    System.out.println("Error ocuure : io exception”);

}
// closing the socket

socket.close();

Sachin Patel

Sachin Patel | Android Developer

I am an Android Developer at Yudiz Solutions Pvt. Ltd. - a mobile App Development company. I am passionate about android app development and like adopting new technologies to maximize development efficiency and produce innovative applications.

Viewing all articles
Browse latest Browse all 595

Trending Articles