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

Sunday, 4 June 2017

Scan Devices IP connected in WiFi network


Example to scan connected devices within the same WiFi network, using InetAddress.isReachable().


package com.blogspot.android_er.androidwireless;

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

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

TextView tvWifiState;
TextView tvScanning, tvResult;

ArrayList<InetAddress> inetAddresses;

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

tvWifiState = (TextView)findViewById(R.id.WifiState);
tvScanning = (TextView)findViewById(R.id.Scanning);
tvResult = (TextView)findViewById(R.id.Result);

//To prevent memory leaks on devices prior to Android N,
//retrieve WifiManager with
//getApplicationContext().getSystemService(Context.WIFI_SERVICE),
//instead of getSystemService(Context.WIFI_SERVICE)
WifiManager wifiManager =
(WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
tvWifiState.setText(readtvWifiState(wifiManager));

new ScanTask(tvScanning, tvResult).execute();
}

// "android.permission.ACCESS_WIFI_STATE" is needed
private String readtvWifiState(WifiManager wm){
String result = "";
switch (wm.getWifiState()){
case WifiManager.WIFI_STATE_DISABLED:
result = "WIFI_STATE_DISABLED";
break;
case WifiManager.WIFI_STATE_DISABLING:
result = "WIFI_STATE_DISABLING";
break;
case WifiManager.WIFI_STATE_ENABLED:
result = "WIFI_STATE_ENABLED";
break;
case WifiManager.WIFI_STATE_ENABLING:
result = "WIFI_STATE_ENABLING";
break;
case WifiManager.WIFI_STATE_UNKNOWN:
result = "WIFI_STATE_UNKNOWN";
break;
default:
}
return result;
}

private class ScanTask extends AsyncTask<Void, String, Void> {

TextView tvCurrentScanning, tvScanResullt;
ArrayList<String> canonicalHostNames;

public ScanTask(TextView tvCurrentScanning, TextView tvScanResullt) {
this.tvCurrentScanning = tvCurrentScanning;
this.tvScanResullt = tvScanResullt;
}

@Override
protected void onPostExecute(Void aVoid) {
tvCurrentScanning.setText("Finished.");
tvScanResullt.setText("");
for(int i = 0; i < inetAddresses.size(); i++){
tvScanResullt.append(canonicalHostNames.get(i) + "\n");
}
}

@Override
protected Void doInBackground(Void... voids) {
scanInetAddresses();
return null;
}

@Override
protected void onProgressUpdate(String... values) {
tvCurrentScanning.setText(values[0]);
}

private void scanInetAddresses(){
//May be you have to adjust the timeout
final int timeout = 500;

if(inetAddresses == null){
inetAddresses = new ArrayList<>();
}
inetAddresses.clear();

if(canonicalHostNames == null){
canonicalHostNames = new ArrayList<>();
}
canonicalHostNames.clear();

//For demonstration, scan 192.168.1.xxx only
byte[] ip = {(byte) 192, (byte) 168, (byte) 1, 0};
for (int j = 0; j < 255; j++) {
ip[3] = (byte) j;
try {
InetAddress checkAddress = InetAddress.getByAddress(ip);
publishProgress(checkAddress.getCanonicalHostName());
if (checkAddress.isReachable(timeout)) {
inetAddresses.add(checkAddress);
canonicalHostNames.add(checkAddress.getCanonicalHostName());
}
} catch (UnknownHostException e) {
e.printStackTrace();
publishProgress(e.getMessage());
} catch (IOException e) {
e.printStackTrace();
publishProgress(e.getMessage());
}
}
}
}
}


<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:orientation="vertical"
tools:context="com.blogspot.android_er.androidwireless.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/WifiState"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Scanning: "/>
<TextView
android:id="@+id/Scanning"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="italic"/>
</LinearLayout>

<TextView
android:id="@+id/Result"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="bold"/>

</LinearLayout>


uses-permission of "android.permission.ACCESS_WIFI_STATE" and "android.permission.INTERNET" are needed.

Saturday, 3 June 2017

Get ssid of connected network and my IP address

Android example code to get ssid and IP address, using WifiInfo.

Tested on Samsung Galaxy A9, running Android 6.0.1.

Wifi enabled and connected

Wifi disabled

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

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

public class MainActivity extends AppCompatActivity {

TextView tvWifiEnabled, tvWifiState, tvWifiInfo, tvSSID,
tvRssi, tvIP, tvFormattedIP1, tvFormattedIP2;

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

tvWifiEnabled = (TextView)findViewById(R.id.WifiEnabled);
tvWifiState = (TextView)findViewById(R.id.WifiState);
tvWifiInfo = (TextView)findViewById(R.id.WifiInfo);
tvSSID = (TextView)findViewById(R.id.SSID);
tvRssi = (TextView)findViewById(R.id.Rssi);
tvIP = (TextView)findViewById(R.id.IP);
tvFormattedIP1 = (TextView)findViewById(R.id.FormattedIP1);
tvFormattedIP2 = (TextView)findViewById(R.id.FormattedIP2);

//To prevent memory leaks on devices prior to Android N,
//retrieve WifiManager with
//getApplicationContext().getSystemService(Context.WIFI_SERVICE),
//instead of getSystemService(Context.WIFI_SERVICE)
WifiManager wifiManager =
(WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
tvWifiEnabled.setText("isWifiEnabled(): " + wifiManager.isWifiEnabled());
tvWifiState.setText(readtvWifiState(wifiManager));

WifiInfo wifiInfo = wifiManager.getConnectionInfo();
if(wifiInfo == null){
tvWifiInfo.setText("wifiInfo == null !!!");
}else{
tvWifiInfo.setText(wifiInfo.toString());
tvSSID.setText("SSID: " + wifiInfo.getSSID());
tvRssi.setText("Rssi: " + wifiInfo.getRssi() + " dBm");

int ipAddress = wifiInfo.getIpAddress();
/*
Formatter.formatIpAddress() was deprecated in API level 12.
This method does not support IPv6 addresses.
*/
String FormatedIpAddress = Formatter.formatIpAddress(ipAddress);
String FormatedIpAddress2 = String.format("%d.%d.%d.%d",
(ipAddress & 0xff),
(ipAddress >> 8 & 0xff),
(ipAddress >> 16 & 0xff),
(ipAddress >> 24 & 0xff));
tvIP.setText("IP: " + wifiInfo.getIpAddress());
tvFormattedIP1.setText("" + FormatedIpAddress);
tvFormattedIP2.setText("" + FormatedIpAddress2);
}

}

// "android.permission.ACCESS_WIFI_STATE" is needed
private String readtvWifiState(WifiManager wm){
String result = "";
switch (wm.getWifiState()){
case WifiManager.WIFI_STATE_DISABLED:
result = "WIFI_STATE_DISABLED";
break;
case WifiManager.WIFI_STATE_DISABLING:
result = "WIFI_STATE_DISABLING";
break;
case WifiManager.WIFI_STATE_ENABLED:
result = "WIFI_STATE_ENABLED";
break;
case WifiManager.WIFI_STATE_ENABLING:
result = "WIFI_STATE_ENABLING";
break;
case WifiManager.WIFI_STATE_UNKNOWN:
result = "WIFI_STATE_UNKNOWN";
break;
default:
}
return result;
}
}


layout
<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:orientation="vertical"
tools:context="com.blogspot.android_er.androidwireless.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/WifiEnabled"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/WifiState"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/WifiInfo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="italic"/>
<TextView
android:id="@+id/SSID"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textColor="#FF0000"/>
<TextView
android:id="@+id/Rssi"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#00FF00"/>
<TextView
android:id="@+id/comment1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="bold"
android:text="get IP Address:"/>
<TextView
android:id="@+id/IP"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="italic"
android:textColor="#0000FF"/>
<TextView
android:id="@+id/FormattedIP1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="italic"
android:textColor="#0000FF"/>
<TextView
android:id="@+id/FormattedIP2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="italic"
android:textColor="#0000FF"/>

</LinearLayout>


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

Remark on MAC:
Please take a look on the captured screen; the MAC address is 02:00:00:00:00:00.

Refer to Android 6.0 Changes - Access to Hardware Identifier:
To provide users with greater data protection, starting in this release, Android removes programmatic access to the device�s local hardware identifier for apps using the Wi-Fi and Bluetooth APIs. The WifiInfo.getMacAddress() and the BluetoothAdapter.getAddress() methods now return a constant value of 02:00:00:00:00:00.

Monday, 23 May 2016

Android client to send message to Java server on Raspberry Pi


It's a Java client and server exercise in my another blogspot HelloraspberryPi. The client connect to server and send something, the server simple print the received message and close.

It's Android version of the client, to connect to server and send something.


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

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class MainActivity extends AppCompatActivity {

EditText editTextAddress, editTextPort, editTextMsg;
Button buttonConnect;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextAddress = (EditText) findViewById(R.id.address);
editTextPort = (EditText) findViewById(R.id.port);
editTextMsg = (EditText) findViewById(R.id.msgtosend);
buttonConnect = (Button) findViewById(R.id.connect);

buttonConnect.setOnClickListener(buttonConnectOnClickListener);
}

View.OnClickListener buttonConnectOnClickListener =
new View.OnClickListener() {

@Override
public void onClick(View arg0) {
MyClientTask myClientTask = new MyClientTask(
editTextAddress.getText().toString(),
Integer.parseInt(editTextPort.getText().toString()));
myClientTask.execute(editTextMsg.getText().toString());
}
};

public class MyClientTask extends AsyncTask<String, Void, Void> {

String dstAddress;
int dstPort;
String response;

MyClientTask(String addr, int port) {
dstAddress = addr;
dstPort = port;
}

@Override
protected Void doInBackground(String... params) {
try {
Socket socket = new Socket(dstAddress, dstPort);

OutputStream outputStream = socket.getOutputStream();
PrintStream printStream = new PrintStream(outputStream);
printStream.print(params[0]);

socket.close();

} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}

}
}


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.androidclient.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" />
<EditText
android:id="@+id/address"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="dstAddress" />
<EditText
android:id="@+id/port"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="dstPort" />
<EditText
android:id="@+id/msgtosend"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="msg to send..." />
<Button
android:id="@+id/connect"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Connect and send..."/>

</LinearLayout>


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

The Java code of the server side, refer to "Java Network exercise: client and server - client send something to server".

The next example "Android client example 2, communicate with Java Server run on Raspberry Pi" show how Android Client connect to Java Server (run on raspberry Pi) and keep connected, and send to and receive from Server.