Semester-IV Project Report Document Project Title: WiFi Connect Akash Rajguru(BSIT/11/10) B.Sc. IT Semester-IV Introduction The project titled Wifi Connect is an Android application to send text message and data(files) on an wifi Ad hoc network . The project Wifi Connect is developed in Android platform by using java as backend language , which mainly focuses on sending text message and data(files) between two android devices using their wifi as a communication medium . The Wifi Connect has five modules. The basic idea behind implementing these modules is to understand some concepts such as:- How two java programs communicates through java socket programming . How to enable wifi through android application How socket programming works in client\server android application How socket programming can be implemented is android app to send text message from android application to server program running on different pcs. How to send data (files ) between two android devices using wifi Direct.
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
IntroductionThe project titled Wifi Connect is an Android application to send text message and data(files) on an wifi Ad hoc network . The project Wifi Connect is developed in Android platform by using java as backend language , which mainly focuses on sending text message and data(files) between two android devices using their wifi as a communication medium .
The Wifi Connect has five modules.
The basic idea behind implementing these modules is to understand some concepts such as:-
How two java programs communicates through java socket programming . How to enable wifi through android application How socket programming works in client\server android application How socket programming can be implemented is android app to send text message
from android application to server program running on different pcs. How to send data (files ) between two android devices using wifi Direct.
The Wifi Connect modules1. Client\Server Socket Programming Module. 2. Wifi on off Button .3. Server Socket & Client Socket android application .4. Wifi Demo .5. Wifi Direct Demo
Project functionality The main aim of this project is to send data on wifi ad hoc network
Guidance taken from Prashant Hinduja(HOD) Jitendra Kumar
Hardware & Software Configuration
For Computer
Processor : Intel® Core™2 Duo processor T7500
RAM : 3GB
Hard Disk : 70GB
Wireless Communication : Intel® Wireless WiFi network adapter
Software
Operating System : Windows 7
Software required building Android application : eclipse-SDK-3.8-win32
: android-sdk_r12-windows
For Android Phone
Operating System : Android OS, v4.0 (Ice Cream Sandwich)
CPU : 1 GHz Cortex-A5
RAM : - 512 MB
WiFi : 802.11b/g/n 2.4GHz
WiFi Direct : YES
Connector : USB 2.0
Socket Programming Module 1Socket programming is most important concept which is going to be implemented in project. In this module I have worked and learned the basics of socket programming. I have understood how client server communicates through the socket programs. I have made a client server program which communicates on two different Linux machines.
public class ServerSide implements Runnable{ Frame f; Socket s; BufferedReader br; BufferedWriter bw; TextField text; Button button1,button2; List list; ServerSocket s1;
public static void main(String arg[]){new ServerSide();
}public ServerSide(){
f=new Frame("Server Application:"); f.setSize(200,300); f.setLayout(new BorderLayout()); button1 = new Button("send"); button2 = new Button("exit"); list =new List(); text =new TextField(); f.add(list,"Center"); f.add(button1,"West"); f.add(button2,"East"); f.add(text,"South"); f.setVisible(true);try{
ServerSocket s1 = new ServerSocket(8080);
// s1 = new ServerScoket(100);
s = s1.accept(); br = new BufferedReader(new InputStreamReader(s.getInputStream())); bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));bw.write("hello");bw.newLine();bw.flush();Thread th;th = new Thread(this);th.start();}catch(Exception e){}
public class ClineSide implements Runnable{ Frame f; BufferedReader br; BufferedWriter bw; TextField text; Button button1,button2; List list; Socket s;
public static void main(String arg[]){new ClineSide();
}public ClineSide(){
f=new Frame("Clint Application:"); f.setSize(200,300); f.setLayout(new BorderLayout()); button1 = new Button("send"); button2 = new Button("exit"); list =new List(); text =new TextField(); f.add(list,"Center"); f.add(button1,"West"); f.add(button2,"East"); f.add(text,"South");
f.setVisible(true);try{
// ServerSocket s1 = new ServerSocket(100);
// s1 = new ServerScoket(100); s = new Socket("192.168.0.145",8080); br = new BufferedReader(new InputStreamReader(s.getInputStream())); bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));bw.write("hello");bw.newLine();bw.flush();Thread th;th = new Thread(this);th.start();
}catch(Exception e){}/*}
public void actionPerformed(ActionEvent e){if (e.getSource().equals(button2)) System.exit(0);
// TODO Auto-generated method stubint extraWifiState =
intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE , WifiManager.WIFI_STATE_UNKNOWN); switch(extraWifiState){ case WifiManager.WIFI_STATE_DISABLED: WifiState.setText("WIFI STATE DISABLED"); break; case WifiManager.WIFI_STATE_DISABLING: WifiState.setText("WIFI STATE DISABLING"); break; case WifiManager.WIFI_STATE_ENABLED: WifiState.setText("WIFI STATE ENABLED"); break; case WifiManager.WIFI_STATE_ENABLING: WifiState.setText("WIFI STATE ENABLING");
break; case WifiManager.WIFI_STATE_UNKNOWN: WifiState.setText("WIFI STATE UNKNOWN"); break; }
}};
}
Snapshot
Module -3: Server Socket & Client Socket in Android ApplicationIn this module I have created two android applications one is Server Socket which is a server application and another is Client Socket which is client application. Here Server Socket application sends message to Client Socket application on local host and client application replies for the message. It is a basic application to demonstrate socket programming in android.
// TODO Auto-generated method stubint extraWifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE ,
WifiManager.WIFI_STATE_UNKNOWN); switch(extraWifiState){ case WifiManager.WIFI_STATE_DISABLED: WifiState.setText("WIFI STATE DISABLED"); break; case WifiManager.WIFI_STATE_DISABLING: WifiState.setText("WIFI STATE DISABLING"); break; case WifiManager.WIFI_STATE_ENABLED: WifiState.setText("WIFI STATE ENABLED"); break; case WifiManager.WIFI_STATE_ENABLING: WifiState.setText("WIFI STATE ENABLING"); break; case WifiManager.WIFI_STATE_UNKNOWN:
Module-4: Wifi Demo (client application)In this module I have created an android client side application which takes ip address and the port number as user input (from text field) and also takes text message as input from user and sends that text message to particular server program ip specified by user on a network. The basic idea is to send text message to the particular computer( which is running server program in it ) through ip address & port number in network.
Snapshot for Server program running on linux machine
Module-5: Wifi Direct Demo Android application In this module I have created an android application which can able to send image (jpg) file and text
(.txt ) file from one android device to another android device in an Ad hoc wifi network. The modification done is before was only able to transfer image file, after modification it can able to sent text file as well.
// UI update to indicate wifi p2p status. int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1); if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) { // Wifi Direct mode is enabled activity.setIsWifiP2pEnabled(true);
} Log.d(WiFiDirectActivity.TAG, "P2P state changed - " + state); } else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
// request available peers from the wifi p2p manager. This is an // asynchronous call and the calling activity is notified with a // callback on PeerListListener.onPeersAvailable() if (manager != null) { manager.requestPeers(channel, (PeerListListener) activity.getFragmentManager() .findFragmentById(R.id.frag_list)); } Log.d(WiFiDirectActivity.TAG, "P2P peers changed"); } else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
* A fragment that manages a particular peer and allows interaction with device * i.e. setting up network connection and transferring data. */public class DeviceDetailFragment extends Fragment implements ConnectionInfoListener {
@Override public void onClick(View v) { WifiP2pConfig config = new WifiP2pConfig(); config.deviceAddress = device.deviceAddress; config.wps.setup = WpsInfo.PBC; if (progressDialog != null && progressDialog.isShowing()) { progressDialog.dismiss(); } progressDialog = ProgressDialog.show(getActivity(), "Press back to cancel", "Connecting to :" + device.deviceAddress, true, true// new DialogInterface.OnCancelListener() {//// @Override// public void onCancel(DialogInterface dialog) {// ((DeviceActionListener) getActivity()).cancelDisconnect();// }// } ); ((DeviceActionListener) getActivity()).connect(config);
} });
mContentView.findViewById(R.id.btn_disconnect).setOnClickListener( new View.OnClickListener() {
@Override public void onClick(View v) { ((DeviceActionListener) getActivity()).disconnect(); } });
mContentView.findViewById(R.id.btn_start_client).setOnClickListener( new View.OnClickListener() {
@Override public void onClick(View v) { // Allow user to pick an image from Gallery or other // registered apps Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("text/*"); startActivityForResult(intent, CHOOSE_FILE_RESULT_CODE); } }); mContentView.findViewById(R.id.btn_start_client1).setOnClickListener( new View.OnClickListener() {
@Override public void onClick(View v) { // Allow user to pick an image from Gallery or other // registered apps Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("image/*"); startActivityForResult(intent, CHOOSE_FILE_RESULT_CODE); } }); return mContentView; }
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// User has picked an image. Transfer it to group owner i.e peer using // FileTransferService. Uri uri = data.getData(); TextView statusText = (TextView) mContentView.findViewById(R.id.status_text); statusText.setText("Sending: " + uri); Log.d(WiFiDirectActivity.TAG, "Intent----------- " + uri); Intent serviceIntent = new Intent(getActivity(), FileTransferService.class); serviceIntent.setAction(FileTransferService.ACTION_SEND_FILE); serviceIntent.putExtra(FileTransferService.EXTRAS_FILE_PATH, uri.toString()); serviceIntent.putExtra(FileTransferService.EXTRAS_GROUP_OWNER_ADDRESS, info.groupOwnerAddress.getHostAddress()); serviceIntent.putExtra(FileTransferService.EXTRAS_GROUP_OWNER_PORT, 8988); getActivity().startService(serviceIntent); }
@Override public void onConnectionInfoAvailable(final WifiP2pInfo info) { if (progressDialog != null && progressDialog.isShowing()) { progressDialog.dismiss(); } this.info = info; this.getView().setVisibility(View.VISIBLE);
// The owner IP is now known. TextView view = (TextView) mContentView.findViewById(R.id.group_owner); view.setText(getResources().getString(R.string.group_owner_text) + ((info.isGroupOwner == true) ? getResources().getString(R.string.yes) : getResources().getString(R.string.no)));
// InetAddress from WifiP2pInfo struct. view = (TextView) mContentView.findViewById(R.id.device_info); view.setText("Group Owner IP - " + info.groupOwnerAddress.getHostAddress());
// After the group negotiation, we assign the group owner as the file // server. The file server is single threaded, single connection server // socket. if (info.groupFormed && info.isGroupOwner) { new FileServerAsyncTask(getActivity(), mContentView.findViewById(R.id.status_text)) .execute(); } else if (info.groupFormed) {
// The other device acts as the client. In this case, we enable the // get file button. mContentView.findViewById(R.id.btn_start_client).setVisibility(View.VISIBLE); ((TextView) mContentView.findViewById(R.id.status_text)).setText(getResources() .getString(R.string.client_text)); }
// hide the connect button mContentView.findViewById(R.id.btn_connect).setVisibility(View.GONE); }
/** * Updates the UI with device data * * @param device the device to be displayed */ public void showDetails(WifiP2pDevice device) { this.device = device; this.getView().setVisibility(View.VISIBLE); TextView view = (TextView) mContentView.findViewById(R.id.device_address); view.setText(device.deviceAddress); view = (TextView) mContentView.findViewById(R.id.device_info); view.setText(device.toString());
}
/** * Clears the UI fields after a disconnect or direct mode disable operation. */ public void resetViews() { mContentView.findViewById(R.id.btn_connect).setVisibility(View.VISIBLE); TextView view = (TextView) mContentView.findViewById(R.id.device_address); view.setText(R.string.empty); view = (TextView) mContentView.findViewById(R.id.device_info); view.setText(R.string.empty); view = (TextView) mContentView.findViewById(R.id.group_owner); view.setText(R.string.empty); view = (TextView) mContentView.findViewById(R.id.status_text); view.setText(R.string.empty); mContentView.findViewById(R.id.btn_start_client).setVisibility(View.GONE); this.getView().setVisibility(View.GONE); }
/** * A simple server socket that accepts connection and writes some data on * the stream. */ public static class FileServerAsyncTask extends AsyncTask<Void, Void, String> {
/* * (non-Javadoc) * @see android.os.AsyncTask#onPreExecute() */ @Override protected void onPreExecute() { statusText.setText("Opening a server socket"); }
}
public static boolean copyFile(InputStream inputStream, OutputStream out) { byte buf[] = new byte[1024]; int len; long startTime=System.currentTimeMillis(); try { while ((len = inputStream.read(buf)) != -1) { out.write(buf, 0, len); } out.close();
inputStream.close(); long endTime=System.currentTimeMillis()-startTime; Log.v("","Time taken to transfer all bytes is : "+endTime); } catch (IOException e) { Log.d(WiFiDirectActivity.TAG, e.toString()); return false; } return true; }
/** * A fragment that manages a particular peer and allows interaction with device * i.e. setting up network connection and transferring data. */public class DeviceDetailFragment extends Fragment implements ConnectionInfoListener {
mContentView.findViewById(R.id.btn_disconnect).setOnClickListener( new View.OnClickListener() {
@Override public void onClick(View v) { ((DeviceActionListener) getActivity()).disconnect(); } });
mContentView.findViewById(R.id.btn_start_client).setOnClickListener( new View.OnClickListener() {
@Override public void onClick(View v) { // Allow user to pick an image from Gallery or other // registered apps Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("text/*"); startActivityForResult(intent, CHOOSE_FILE_RESULT_CODE); } }); mContentView.findViewById(R.id.btn_start_client1).setOnClickListener( new View.OnClickListener() {
@Override public void onClick(View v) { // Allow user to pick an image from Gallery or other // registered apps Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("image/*"); startActivityForResult(intent, CHOOSE_FILE_RESULT_CODE);
} }); return mContentView; }
@Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
// User has picked an image. Transfer it to group owner i.e peer using // FileTransferService. Uri uri = data.getData(); TextView statusText = (TextView) mContentView.findViewById(R.id.status_text); statusText.setText("Sending: " + uri); Log.d(WiFiDirectActivity.TAG, "Intent----------- " + uri); Intent serviceIntent = new Intent(getActivity(), FileTransferService.class); serviceIntent.setAction(FileTransferService.ACTION_SEND_FILE); serviceIntent.putExtra(FileTransferService.EXTRAS_FILE_PATH, uri.toString()); serviceIntent.putExtra(FileTransferService.EXTRAS_GROUP_OWNER_ADDRESS, info.groupOwnerAddress.getHostAddress()); serviceIntent.putExtra(FileTransferService.EXTRAS_GROUP_OWNER_PORT, 8988); getActivity().startService(serviceIntent); }
@Override public void onConnectionInfoAvailable(final WifiP2pInfo info) { if (progressDialog != null && progressDialog.isShowing()) { progressDialog.dismiss(); } this.info = info; this.getView().setVisibility(View.VISIBLE);
// The owner IP is now known. TextView view = (TextView) mContentView.findViewById(R.id.group_owner); view.setText(getResources().getString(R.string.group_owner_text) + ((info.isGroupOwner == true) ? getResources().getString(R.string.yes) : getResources().getString(R.string.no)));
// InetAddress from WifiP2pInfo struct. view = (TextView) mContentView.findViewById(R.id.device_info); view.setText("Group Owner IP - " + info.groupOwnerAddress.getHostAddress());
// After the group negotiation, we assign the group owner as the file // server. The file server is single threaded, single connection server // socket. if (info.groupFormed && info.isGroupOwner) { new FileServerAsyncTask(getActivity(), mContentView.findViewById(R.id.status_text)) .execute(); } else if (info.groupFormed) { // The other device acts as the client. In this case, we enable the // get file button. mContentView.findViewById(R.id.btn_start_client).setVisibility(View.VISIBLE); ((TextView) mContentView.findViewById(R.id.status_text)).setText(getResources() .getString(R.string.client_text)); }
// hide the connect button mContentView.findViewById(R.id.btn_connect).setVisibility(View.GONE); }
/** * Updates the UI with device data * * @param device the device to be displayed */ public void showDetails(WifiP2pDevice device) { this.device = device; this.getView().setVisibility(View.VISIBLE); TextView view = (TextView) mContentView.findViewById(R.id.device_address); view.setText(device.deviceAddress); view = (TextView) mContentView.findViewById(R.id.device_info); view.setText(device.toString());
}
/** * Clears the UI fields after a disconnect or direct mode disable operation. */ public void resetViews() { mContentView.findViewById(R.id.btn_connect).setVisibility(View.VISIBLE); TextView view = (TextView) mContentView.findViewById(R.id.device_address); view.setText(R.string.empty); view = (TextView) mContentView.findViewById(R.id.device_info); view.setText(R.string.empty);
/** * A simple server socket that accepts connection and writes some data on * the stream. */ public static class FileServerAsyncTask extends AsyncTask<Void, Void, String> {
/** * A service that process each file transfer request i.e Intent by opening a * socket connection with the WiFi Direct Group Owner and writing the file
*/public class FileTransferService extends IntentService {
private static final int SOCKET_TIMEOUT = 5000; public static final String ACTION_SEND_FILE = "com.example.android.wifidirect.SEND_FILE"; public static final String EXTRAS_FILE_PATH = "file_url"; public static final String EXTRAS_GROUP_OWNER_ADDRESS = "go_host"; public static final String EXTRAS_GROUP_OWNER_PORT = "go_port";
public FileTransferService(String name) { super(name); }
public FileTransferService() { super("FileTransferService"); }
/** * An activity that uses WiFi Direct APIs to discover and connect with available * devices. WiFi Direct APIs are asynchronous and rely on callback mechanism * using interfaces to notify the application of operation success or failure. * The application should also register a BroadcastReceiver for notification of * WiFi state related events. */public class WiFiDirectActivity extends Activity implements ChannelListener, DeviceActionListener {
public static final String TAG = "wifidirectdemo"; private WifiP2pManager manager; private boolean isWifiP2pEnabled = false; private boolean retryChannel = false;
private final IntentFilter intentFilter = new IntentFilter(); private Channel channel; private BroadcastReceiver receiver = null;
/** * @param isWifiP2pEnabled the isWifiP2pEnabled to set */ public void setIsWifiP2pEnabled(boolean isWifiP2pEnabled) { this.isWifiP2pEnabled = isWifiP2pEnabled; }
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);
/** register the BroadcastReceiver with the intent values to be matched */ @Override public void onResume() { super.onResume(); receiver = new WiFiDirectBroadcastReceiver(manager, channel, this); registerReceiver(receiver, intentFilter); }
@Override public void onPause() { super.onPause(); unregisterReceiver(receiver); }
/** * Remove all peers and clear all fields. This is called on * BroadcastReceiver receiving a state change event. */ public void resetData() { DeviceListFragment fragmentList = (DeviceListFragment) getFragmentManager() .findFragmentById(R.id.frag_list); DeviceDetailFragment fragmentDetails = (DeviceDetailFragment) getFragmentManager() .findFragmentById(R.id.frag_detail); if (fragmentList != null) { fragmentList.clearPeers(); } if (fragmentDetails != null) { fragmentDetails.resetViews(); } }
/* * (non-Javadoc) * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem) */ @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.atn_direct_enable: if (manager != null && channel != null) {
// Since this is the system wireless settings activity, it's // not going to send us a result. We will be notified by // WiFiDeviceBroadcastReceiver instead.
startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS)); } else { Log.e(TAG, "channel or manager is null"); } return true;
case R.id.atn_direct_discover: if (!isWifiP2pEnabled) { Toast.makeText(WiFiDirectActivity.this, R.string.p2p_off_warning, Toast.LENGTH_SHORT).show(); return true; } final DeviceListFragment fragment = (DeviceListFragment) getFragmentManager() .findFragmentById(R.id.frag_list); fragment.onInitiateDiscovery(); manager.discoverPeers(channel, new WifiP2pManager.ActionListener() {
@Override public void onSuccess() { Toast.makeText(WiFiDirectActivity.this, "Discovery Initiated", Toast.LENGTH_SHORT).show(); }
@Override public void disconnect() { final DeviceDetailFragment fragment = (DeviceDetailFragment) getFragmentManager() .findFragmentById(R.id.frag_detail); fragment.resetViews(); manager.removeGroup(channel, new ActionListener() {
@Override public void onSuccess() { fragment.getView().setVisibility(View.GONE); }
}); }
@Override public void onChannelDisconnected() { // we will try once more if (manager != null && !retryChannel) { Toast.makeText(this, "Channel lost. Trying again", Toast.LENGTH_LONG).show(); resetData(); retryChannel = true; manager.initialize(this, getMainLooper(), this); } else { Toast.makeText(this, "Severe! Channel is probably lost premanently. Try Disable/Re-Enable P2P.", Toast.LENGTH_LONG).show(); } }
@Override public void cancelDisconnect() {
/* * A cancel abort request by user. Disconnect i.e. removeGroup if * already connected. Else, request WifiP2pManager to abort the ongoing * request */ if (manager != null) { final DeviceListFragment fragment = (DeviceListFragment) getFragmentManager() .findFragmentById(R.id.frag_list); if (fragment.getDevice() == null || fragment.getDevice().status == WifiP2pDevice.CONNECTED) { disconnect();