SlideShare uma empresa Scribd logo
1 de 55
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 clientserver 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 modules

1.
2.
3.
4.
5.

ClientServer Socket Programming Module.
Wifi on off Button .
Server Socket & Client Socket android application .
Wifi Demo .
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 1
Socket 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.

Class Diagram

Deployment Diagram

ServerSide.java
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Frame;
import java.awt.List;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.*;
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){}
button1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
try{
bw.write(text.getText());
bw.newLine();
bw.flush();
text.setText("");
}
catch(Exception n){}
}
});
button2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
System.exit(0);
}
});
}
public void run()
{
try
{
s1.setSoTimeout(1);
}
catch(Exception e){}
while(true)
{
try
{
list.addItem(br.readLine());
}
catch(Exception h){}
}
}
}
Snapshot

clinSide.java
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Frame;
import java.awt.List;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.*;

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);
else{
try
{
bw.write(text.getText());
bw.newLine();
bw.flush();
text.setText("");
}catch(Exception m){}
}
}
*/
button1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
try{
bw.write(text.getText());
bw.newLine();
bw.flush();
text.setText("");
}
catch(Exception n){}
}
});
button2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
System.exit(0);
}
});
}
public void run()
{
try
{
s.setSoTimeout(1);
}
catch(Exception e){}
while(true)
{
try
{
list.addItem(br.readLine());
}
catch(Exception h){}
}
}
}
Snapshot

Module 2 WiFi On Off button
In this module I have worked and learned how to enable and disable a wifi on device by using
wifiManager .

public class MainActivity extends Activity {
//private static final BroadcastReceiver WifiStateChangedReceiver = null;
TextView WifiState;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WifiState = (TextView)findViewById(R.id.wifistate);
Button OnWifi = (Button)findViewById(R.id.onwifi);
Button OffWifi = (Button)findViewById(R.id.offwifi);
this.registerReceiver(this.WifiStateChangedReceiver,
new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION));
OnWifi.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
WifiManager wifiManager =
(WifiManager)getBaseContext().getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
}});
OffWifi.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
WifiManager wifiManager =
(WifiManager)getBaseContext().getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(false);
}});
}
private BroadcastReceiver WifiStateChangedReceiver
= new BroadcastReceiver(){

@Override
public void onReceive(Context context, Intent intent) {

// TODO Auto-generated method stub
int 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 Application
In 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.

Server Socket application code
MyServer.java
package edu.amplify.serversocket;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
mport android.os.Handler;
import android.os.Message;
public class MyServer {
Thread m_objThread;
ServerSocket m_server;
String m_strMessage;
DataDisplay m_dataDisplay;
Object m_connected;
public MyServer()
{
}
public void setEventListener(DataDisplay dataDispaly)
{
m_dataDisplay= dataDispaly;

}
public void startListening()
{
m_objThread= new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
try
{
m_server=new ServerSocket(2001);
Socket connectedSocket = m_server.accept();
Message clientmessage= Message.obtain();
ObjectInputStream ois = new
ObjectInputStream(connectedSocket.getInputStream());
String strMessage = (String)ois.readObject();
clientmessage.obj=strMessage;
mHandler.sendMessage(clientmessage);
ObjectOutputStream oos=new
ObjectOutputStream(connectedSocket.getOutputStream());
oos.writeObject("hai...client this is server");
ois.close();
oos.close();
m_server.close();
}
catch(Exception e)
{
Message msg3 = Message.obtain();
msg3.obj=e.getMessage();
mHandler.sendMessage(msg3);
}
}
});
m_objThread.start();
}
Handler mHandler = new Handler()
{
public void handleMessage(Message status){
m_dataDisplay.Display(status.obj.toString());
}
};
}
DataDisplay.java
package edu.amplify.serversocket;
public interface DataDisplay {
void Display(String message);
}

MainActivity.java
ackage edu.amplify.wifinooff;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
//private static final BroadcastReceiver WifiStateChangedReceiver = null;
TextView WifiState;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WifiState = (TextView)findViewById(R.id.wifistate);
Button OnWifi = (Button)findViewById(R.id.onwifi);
Button OffWifi = (Button)findViewById(R.id.offwifi);
this.registerReceiver(this.WifiStateChangedReceiver,
new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION));
OnWifi.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
WifiManager wifiManager =
(WifiManager)getBaseContext().getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
}});
OffWifi.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
WifiManager wifiManager =
(WifiManager)getBaseContext().getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(false);
}});
}
private BroadcastReceiver WifiStateChangedReceiver
= new BroadcastReceiver(){

@Override
public void onReceive(Context context, Intent intent) {

// TODO Auto-generated method stub
int 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;
}
}};

}

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="edu.amplify.serversocket"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="edu.amplify.serversocket.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Client Socket application code
MainActivity.java
package edu.amplify.clintsocket;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import
import
import
import
import
import
import

android.os.Bundle;
android.os.Handler;
android.os.Message;
android.app.Activity;
android.view.Menu;
android.view.View;
android.widget.TextView;

public class MainActivity extends Activity {
TextView serverMessage;
Thread m_objThreadClient;
Socket clientSocket;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
serverMessage =(TextView)findViewById(R.id.textView1);
}
public void Start(View view)
{
m_objThreadClient=new Thread(new Runnable() {
public void run()
{
try
{
clientSocket= new Socket("127.0.0.1",2001);
ObjectOutputStream oos = new
ObjectOutputStream(clientSocket.getOutputStream());
oos.writeObject("Hellow Server....this client ");
Message serverMessage= Message.obtain();
ObjectInputStream ois =new
ObjectInputStream(clientSocket.getInputStream());
String strMessage = (String)ois.readObject();
serverMessage.obj=strMessage;

mHandler.sendMessage(serverMessage);
oos.close();
ois.close();
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
m_objThreadClient.start();
}
Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
messageDisplay(msg.obj.toString());
}
};
public void messageDisplay(String servermessage)
{
serverMessage.setText(""+servermessage);
}
}

AndroidMenifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="edu.amplify.clintsocket"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="edu.amplify.clintsocket.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Snapshot for Server Socket Application
Snapshot for Client Socket application
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.

Wifi Demo source code

MainActivity.java
package edu.amplify.wifidemo;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
private Socket client;
private PrintWriter printwriter;
private EditText etMsg, etIP, etPort;
private Button button;
private String messsage;
int port = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
etIP = (EditText) findViewById(R.id.editText1);
etPort = (EditText) findViewById(R.id.editText2);
etMsg = (EditText) findViewById(R.id.editText3);
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
messsage = etMsg.getText().toString();
etMsg.setText("");
port = Integer.parseInt(etPort.getText().toString());
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
try
{
client = new Socket(etIP.getText().toString(), port);
// ObjectOutputStream oos = new ObjectOutputStream(client.getOutputStream());
// oos.writeObject(messsage);
printwriter = new PrintWriter(client.getOutputStream());
printwriter.write(messsage);
printwriter.flush();
printwriter.close();
client.close();
}
catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();

}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="edu.amplify.wifidemo"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></usespermission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></usespermission>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="edu.amplify.wifidemo.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Snapshot for Wifi Demo application
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.
Sequence Diagram for wifi direct demo

Wifi Direct Demo source code

WifiDirectBroadcastReceiver.java

package com.example.android.wifidirect;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.NetworkInfo;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pManager;
import android.net.wifi.p2p.WifiP2pManager.Channel;
import android.net.wifi.p2p.WifiP2pManager.PeerListListener;
import android.util.Log;
/**
* A BroadcastReceiver that notifies of important wifi p2p events.
*/
public class WiFiDirectBroadcastReceiver extends BroadcastReceiver {
private WifiP2pManager manager;
private Channel channel;
private WiFiDirectActivity activity;
/**
* @param manager WifiP2pManager system service
* @param channel Wifi p2p channel
* @param activity activity associated with the receiver
*/
public WiFiDirectBroadcastReceiver(WifiP2pManager manager, Channel channel,
WiFiDirectActivity activity) {
super();
this.manager = manager;
this.channel = channel;
this.activity = activity;
}
/*
* (non-Javadoc)
* @see android.content.BroadcastReceiver#onReceive(android.content.Context,
* android.content.Intent)
*/
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {
// 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);
} else {
activity.setIsWifiP2pEnabled(false);
activity.resetData();
}
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)) {
if (manager == null) {
return;
}
NetworkInfo networkInfo = (NetworkInfo) intent
.getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO);
if (networkInfo.isConnected()) {
// we are connected with the other device, request connection
// info to find group owner IP
DeviceDetailFragment fragment = (DeviceDetailFragment) activity
.getFragmentManager().findFragmentById(R.id.frag_detail);
manager.requestConnectionInfo(channel, fragment);
} else {
// It's a disconnect
activity.resetData();
}
} else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {
DeviceListFragment fragment = (DeviceListFragment) activity.getFragmentManager()
.findFragmentById(R.id.frag_list);
fragment.updateThisDevice((WifiP2pDevice) intent.getParcelableExtra(
WifiP2pManager.EXTRA_WIFI_P2P_DEVICE));
}
}
}
DeviceDetailFragment.java

package com.example.android.wifidirect;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.net.wifi.WpsInfo;
import android.net.wifi.p2p.WifiP2pConfig;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pInfo;
import android.net.wifi.p2p.WifiP2pManager.ConnectionInfoListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.android.wifidirect.DeviceListFragment.DeviceActionListener;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
/**
* 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 {
protected static final int CHOOSE_FILE_RESULT_CODE = 20;
private View mContentView = null;
private WifiP2pDevice device;
private WifiP2pInfo info;
ProgressDialog progressDialog = null;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mContentView = inflater.inflate(R.layout.device_detail, null);
mContentView.findViewById(R.id.btn_connect).setOnClickListener(new View.OnClickListener() {

//
//
//
//
//
//
//

@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> {
private Context context;
private TextView statusText;
/**
* @param context
* @param statusText
*/
public FileServerAsyncTask(Context context, View statusText) {
this.context = context;
this.statusText = (TextView) statusText;
}
@Override
protected String doInBackground(Void... params) {
try {
ServerSocket serverSocket = new ServerSocket(8988);
Log.d(WiFiDirectActivity.TAG, "Server: Socket opened");
Socket client = serverSocket.accept();
Log.d(WiFiDirectActivity.TAG, "Server: connection done");
final File f = new File(Environment.getExternalStorageDirectory() + "/"
+ context.getPackageName() + "/wifip2pshared-" + System.currentTimeMillis()
+ ".txt",".jpg");
File dirs = new File(f.getParent());
if (!dirs.exists())
dirs.mkdirs();
f.createNewFile();
Log.d(WiFiDirectActivity.TAG, "server: copying files " + f.toString());
InputStream inputstream = client.getInputStream();
copyFile(inputstream, new FileOutputStream(f));
serverSocket.close();
return f.getAbsolutePath();
} catch (IOException e) {
Log.e(WiFiDirectActivity.TAG, e.getMessage());
return null;
}
}
/*
* (non-Javadoc)
* @see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
@Override
protected void onPostExecute(String result) {
if (result != null) {
statusText.setText("File copied - " + result);
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" + result), "text/*");
intent.setDataAndType(Uri.parse("file://" + result), "image/*");
context.startActivity(intent);
}
}
/*
* (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;
}
}

DeviceListFragment.java
package com.example.android.wifidirect;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.net.wifi.WpsInfo;
import android.net.wifi.p2p.WifiP2pConfig;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pInfo;
import android.net.wifi.p2p.WifiP2pManager.ConnectionInfoListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.android.wifidirect.DeviceListFragment.DeviceActionListener;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
/**
* 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 {
protected static final int CHOOSE_FILE_RESULT_CODE = 20;
private View mContentView = null;
private WifiP2pDevice device;
private WifiP2pInfo info;
ProgressDialog progressDialog = null;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mContentView = inflater.inflate(R.layout.device_detail, null);
mContentView.findViewById(R.id.btn_connect).setOnClickListener(new View.OnClickListener() {

//
//
//

@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> {
private Context context;
private TextView statusText;
/**
* @param context
* @param statusText
*/
public FileServerAsyncTask(Context context, View statusText) {
this.context = context;
this.statusText = (TextView) statusText;
}
@Override
protected String doInBackground(Void... params) {
try {
ServerSocket serverSocket = new ServerSocket(8988);
Log.d(WiFiDirectActivity.TAG, "Server: Socket opened");
Socket client = serverSocket.accept();
Log.d(WiFiDirectActivity.TAG, "Server: connection done");
final File f = new File(Environment.getExternalStorageDirectory() + "/"
+ context.getPackageName() + "/wifip2pshared-" + System.currentTimeMillis()
+ ".txt",".jpg");
File dirs = new File(f.getParent());
if (!dirs.exists())
dirs.mkdirs();
f.createNewFile();
Log.d(WiFiDirectActivity.TAG, "server: copying files " + f.toString());
InputStream inputstream = client.getInputStream();
copyFile(inputstream, new FileOutputStream(f));
serverSocket.close();
return f.getAbsolutePath();
} catch (IOException e) {
Log.e(WiFiDirectActivity.TAG, e.getMessage());
return null;
}
}
/*
* (non-Javadoc)
* @see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
@Override
protected void onPostExecute(String result) {
if (result != null) {
statusText.setText("File copied - " + result);
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" + result), "text/*");
intent.setDataAndType(Uri.parse("file://" + result), "image/*");
context.startActivity(intent);
}
}
/*
* (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;
}
}
FileTransferService.java
// Copyright 2011 Google Inc. All Rights Reserved.
package com.example.android.wifidirect;
import android.app.IntentService;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
/**
* 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");
}
/*
* (non-Javadoc)
* @see android.app.IntentService#onHandleIntent(android.content.Intent)
*/
@Override
protected void onHandleIntent(Intent intent) {
Context context = getApplicationContext();
if (intent.getAction().equals(ACTION_SEND_FILE)) {
String fileUri = intent.getExtras().getString(EXTRAS_FILE_PATH);
String host = intent.getExtras().getString(EXTRAS_GROUP_OWNER_ADDRESS);
Socket socket = new Socket();
int port = intent.getExtras().getInt(EXTRAS_GROUP_OWNER_PORT);
try {
Log.d(WiFiDirectActivity.TAG, "Opening client socket - ");
socket.bind(null);
socket.connect((new InetSocketAddress(host, port)), SOCKET_TIMEOUT);
Log.d(WiFiDirectActivity.TAG, "Client socket - " + socket.isConnected());
OutputStream stream = socket.getOutputStream();
ContentResolver cr = context.getContentResolver();
InputStream is = null;
try {
is = cr.openInputStream(Uri.parse(fileUri));
} catch (FileNotFoundException e) {
Log.d(WiFiDirectActivity.TAG, e.toString());
}
DeviceDetailFragment.copyFile(is, stream);
Log.d(WiFiDirectActivity.TAG, "Client: Data written");
} catch (IOException e) {
Log.e(WiFiDirectActivity.TAG, e.getMessage());
} finally {
if (socket != null) {
if (socket.isConnected()) {
try {
socket.close();
} catch (IOException e) {
// Give up
e.printStackTrace();
}
}
}
}
}
}
}

WifiDirectActivity.java
package com.example.android.wifidirect;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.p2p.WifiP2pConfig;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pManager;
import android.net.wifi.p2p.WifiP2pManager.ActionListener;
import android.net.wifi.p2p.WifiP2pManager.Channel;
import android.net.wifi.p2p.WifiP2pManager.ChannelListener;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.example.android.wifidirect.DeviceListFragment.DeviceActionListener;
/**
* 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);
// add necessary intent values to be matched.
intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
manager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
channel = manager.initialize(this, getMainLooper(), null);
}
/** 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();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.action_items, menu);
return true;
}
/*
* (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 onFailure(int reasonCode) {
Toast.makeText(WiFiDirectActivity.this, "Discovery Failed : " + reasonCode,
Toast.LENGTH_SHORT).show();
}
});
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void showDetails(WifiP2pDevice device) {
DeviceDetailFragment fragment = (DeviceDetailFragment) getFragmentManager()
.findFragmentById(R.id.frag_detail);
fragment.showDetails(device);
}
@Override
public void connect(WifiP2pConfig config) {
manager.connect(channel, config, new ActionListener() {
@Override
public void onSuccess() {
// WiFiDirectBroadcastReceiver will notify us. Ignore for now.
}
@Override
public void onFailure(int reason) {
Toast.makeText(WiFiDirectActivity.this, "Connect failed. Retry.",
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 onFailure(int reasonCode) {
Log.d(TAG, "Disconnect failed. Reason :" + reasonCode);
}
@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();
} else if (fragment.getDevice().status == WifiP2pDevice.AVAILABLE
|| fragment.getDevice().status == WifiP2pDevice.INVITED) {
manager.cancelConnect(channel, new ActionListener() {
@Override
public void onSuccess() {
Toast.makeText(WiFiDirectActivity.this, "Aborting connection",
Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(int reasonCode) {
Toast.makeText(WiFiDirectActivity.this,
"Connect abort request failed. Reason Code: " + reasonCode,
Toast.LENGTH_SHORT).show();
}
});
}
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.wifidirect"
android:versionCode="1" android:versionName="1.0">
<uses-sdk android:minSdkVersion="14" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!-- Market filtering -->
<uses-feature android:name="android.hardware.wifi.direct"
android:required="true"/>
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@android:style/Theme.Holo">
<activity
android:name=".WiFiDirectActivity"
android:label="@string/app_name" android:launchMode="singleTask">
<intent-filter>
<action
android:name="android.intent.action.MAIN" />
<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- Used for transferring files after a successful connection -->
<service android:enabled="true" android:name=".FileTransferService" />
</application>
</manifest>

Snapshots for Wifi Direct Demo application
4th semester project report
4th semester project report

Mais conteúdo relacionado

Mais procurados

project_proposal_osrf
project_proposal_osrfproject_proposal_osrf
project_proposal_osrfom1234567890
 
Architecting your GWT applications with GWT-Platform - Lesson 02
Architecting your GWT applications with GWT-Platform - Lesson 02Architecting your GWT applications with GWT-Platform - Lesson 02
Architecting your GWT applications with GWT-Platform - Lesson 02rhemsolutions
 
Async task, threads, pools, and executors oh my!
Async task, threads, pools, and executors oh my!Async task, threads, pools, and executors oh my!
Async task, threads, pools, and executors oh my!Stacy Devino
 
Basic Gradle Plugin Writing
Basic Gradle Plugin WritingBasic Gradle Plugin Writing
Basic Gradle Plugin WritingSchalk Cronjé
 
Final Project Presentation
Final Project PresentationFinal Project Presentation
Final Project Presentationzroserie
 
Idiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin WritingIdiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin WritingSchalk Cronjé
 

Mais procurados (7)

project_proposal_osrf
project_proposal_osrfproject_proposal_osrf
project_proposal_osrf
 
Architecting your GWT applications with GWT-Platform - Lesson 02
Architecting your GWT applications with GWT-Platform - Lesson 02Architecting your GWT applications with GWT-Platform - Lesson 02
Architecting your GWT applications with GWT-Platform - Lesson 02
 
Async task, threads, pools, and executors oh my!
Async task, threads, pools, and executors oh my!Async task, threads, pools, and executors oh my!
Async task, threads, pools, and executors oh my!
 
Di code steps
Di code stepsDi code steps
Di code steps
 
Basic Gradle Plugin Writing
Basic Gradle Plugin WritingBasic Gradle Plugin Writing
Basic Gradle Plugin Writing
 
Final Project Presentation
Final Project PresentationFinal Project Presentation
Final Project Presentation
 
Idiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin WritingIdiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin Writing
 

Destaque

Relativistic Effect in GPS Satellite and Computation of Time Error
Relativistic Effect in GPS Satellite and Computation of Time Error Relativistic Effect in GPS Satellite and Computation of Time Error
Relativistic Effect in GPS Satellite and Computation of Time Error Vedant Srivastava
 
Mobile communication process or cellular network
Mobile communication process or cellular networkMobile communication process or cellular network
Mobile communication process or cellular networkSudhanshu Jha
 
Gps based vehicle monitoring system copy
Gps based vehicle monitoring system   copyGps based vehicle monitoring system   copy
Gps based vehicle monitoring system copySumit Varshney
 
Wifi direct technology a technical report
Wifi direct technology   a technical reportWifi direct technology   a technical report
Wifi direct technology a technical reportAngelos Alevizopoulos
 
Wireless Mobile Charger by Cellular Network:- My Project
Wireless Mobile Charger by  Cellular Network:- My ProjectWireless Mobile Charger by  Cellular Network:- My Project
Wireless Mobile Charger by Cellular Network:- My ProjectAbhishek Jangid
 
Cellular Communication Report
Cellular Communication ReportCellular Communication Report
Cellular Communication ReportPrashant Gajendra
 
Seminar report on Millimeter Wave mobile communications for 5g cellular
Seminar report on Millimeter Wave mobile communications for 5g cellularSeminar report on Millimeter Wave mobile communications for 5g cellular
Seminar report on Millimeter Wave mobile communications for 5g cellularraghubraghu
 
Millimeter wave mobile communication for 5G cellular.
Millimeter  wave  mobile communication for 5G cellular.Millimeter  wave  mobile communication for 5G cellular.
Millimeter wave mobile communication for 5G cellular.Apurv Modi
 
Vehicle tracking system,be computer android report,android project report,gps...
Vehicle tracking system,be computer android report,android project report,gps...Vehicle tracking system,be computer android report,android project report,gps...
Vehicle tracking system,be computer android report,android project report,gps...Sujit9561
 

Destaque (9)

Relativistic Effect in GPS Satellite and Computation of Time Error
Relativistic Effect in GPS Satellite and Computation of Time Error Relativistic Effect in GPS Satellite and Computation of Time Error
Relativistic Effect in GPS Satellite and Computation of Time Error
 
Mobile communication process or cellular network
Mobile communication process or cellular networkMobile communication process or cellular network
Mobile communication process or cellular network
 
Gps based vehicle monitoring system copy
Gps based vehicle monitoring system   copyGps based vehicle monitoring system   copy
Gps based vehicle monitoring system copy
 
Wifi direct technology a technical report
Wifi direct technology   a technical reportWifi direct technology   a technical report
Wifi direct technology a technical report
 
Wireless Mobile Charger by Cellular Network:- My Project
Wireless Mobile Charger by  Cellular Network:- My ProjectWireless Mobile Charger by  Cellular Network:- My Project
Wireless Mobile Charger by Cellular Network:- My Project
 
Cellular Communication Report
Cellular Communication ReportCellular Communication Report
Cellular Communication Report
 
Seminar report on Millimeter Wave mobile communications for 5g cellular
Seminar report on Millimeter Wave mobile communications for 5g cellularSeminar report on Millimeter Wave mobile communications for 5g cellular
Seminar report on Millimeter Wave mobile communications for 5g cellular
 
Millimeter wave mobile communication for 5G cellular.
Millimeter  wave  mobile communication for 5G cellular.Millimeter  wave  mobile communication for 5G cellular.
Millimeter wave mobile communication for 5G cellular.
 
Vehicle tracking system,be computer android report,android project report,gps...
Vehicle tracking system,be computer android report,android project report,gps...Vehicle tracking system,be computer android report,android project report,gps...
Vehicle tracking system,be computer android report,android project report,gps...
 

Semelhante a 4th semester project report

Vaadin 7 CN
Vaadin 7 CNVaadin 7 CN
Vaadin 7 CNjojule
 
React Native for multi-platform mobile applications
React Native for multi-platform mobile applicationsReact Native for multi-platform mobile applications
React Native for multi-platform mobile applicationsMatteo Manchi
 
Developer Student Clubs NUK - Flutter for Beginners
Developer Student Clubs NUK - Flutter for BeginnersDeveloper Student Clubs NUK - Flutter for Beginners
Developer Student Clubs NUK - Flutter for BeginnersJiaxuan Lin
 
Google Web Toolkits
Google Web ToolkitsGoogle Web Toolkits
Google Web ToolkitsYiguang Hu
 
What's new in Android P @ I/O Extended Bangkok 2018
What's new in Android P @ I/O Extended Bangkok 2018What's new in Android P @ I/O Extended Bangkok 2018
What's new in Android P @ I/O Extended Bangkok 2018Somkiat Khitwongwattana
 
Google Wave API: Now and Beyond
Google Wave API: Now and BeyondGoogle Wave API: Now and Beyond
Google Wave API: Now and BeyondMarakana Inc.
 
Workshop 26: React Native - The Native Side
Workshop 26: React Native - The Native SideWorkshop 26: React Native - The Native Side
Workshop 26: React Native - The Native SideVisual Engineering
 
Java Web Programming on Google Cloud Platform [3/3] : Google Web Toolkit
Java Web Programming on Google Cloud Platform [3/3] : Google Web ToolkitJava Web Programming on Google Cloud Platform [3/3] : Google Web Toolkit
Java Web Programming on Google Cloud Platform [3/3] : Google Web ToolkitIMC Institute
 
[1D1]신개념 N스크린 웹 앱 프레임워크 PARS
[1D1]신개념 N스크린 웹 앱 프레임워크 PARS[1D1]신개념 N스크린 웹 앱 프레임워크 PARS
[1D1]신개념 N스크린 웹 앱 프레임워크 PARSNAVER D2
 
softshake 2014 - Java EE
softshake 2014 - Java EEsoftshake 2014 - Java EE
softshake 2014 - Java EEAlexis Hassler
 
Android presentation
Android presentationAndroid presentation
Android presentationImam Raza
 
Android MVVM architecture using Kotlin, Dagger2, LiveData, MediatorLiveData
Android MVVM architecture using Kotlin, Dagger2, LiveData, MediatorLiveDataAndroid MVVM architecture using Kotlin, Dagger2, LiveData, MediatorLiveData
Android MVVM architecture using Kotlin, Dagger2, LiveData, MediatorLiveDataWaheed Nazir
 
Apache Cordova In Action
Apache Cordova In ActionApache Cordova In Action
Apache Cordova In ActionHazem Saleh
 
Introduction to Things board (An Open Source IoT Cloud Platform)
Introduction to Things board (An Open Source IoT Cloud Platform)Introduction to Things board (An Open Source IoT Cloud Platform)
Introduction to Things board (An Open Source IoT Cloud Platform)Amarjeetsingh Thakur
 
Pavlo Zhdanov "Java and Swift: How to Create Applications for Automotive Head...
Pavlo Zhdanov "Java and Swift: How to Create Applications for Automotive Head...Pavlo Zhdanov "Java and Swift: How to Create Applications for Automotive Head...
Pavlo Zhdanov "Java and Swift: How to Create Applications for Automotive Head...LogeekNightUkraine
 
Java Advance 4deleteQuery.PNGJava Advance 4deleteQuerySucc.docx
Java Advance 4deleteQuery.PNGJava Advance 4deleteQuerySucc.docxJava Advance 4deleteQuery.PNGJava Advance 4deleteQuerySucc.docx
Java Advance 4deleteQuery.PNGJava Advance 4deleteQuerySucc.docxpriestmanmable
 

Semelhante a 4th semester project report (20)

JavaCro'14 - Building interactive web applications with Vaadin – Peter Lehto
JavaCro'14 - Building interactive web applications with Vaadin – Peter LehtoJavaCro'14 - Building interactive web applications with Vaadin – Peter Lehto
JavaCro'14 - Building interactive web applications with Vaadin – Peter Lehto
 
Vaadin 7 CN
Vaadin 7 CNVaadin 7 CN
Vaadin 7 CN
 
React Native for multi-platform mobile applications
React Native for multi-platform mobile applicationsReact Native for multi-platform mobile applications
React Native for multi-platform mobile applications
 
Developer Student Clubs NUK - Flutter for Beginners
Developer Student Clubs NUK - Flutter for BeginnersDeveloper Student Clubs NUK - Flutter for Beginners
Developer Student Clubs NUK - Flutter for Beginners
 
Google Web Toolkits
Google Web ToolkitsGoogle Web Toolkits
Google Web Toolkits
 
What's new in Android P @ I/O Extended Bangkok 2018
What's new in Android P @ I/O Extended Bangkok 2018What's new in Android P @ I/O Extended Bangkok 2018
What's new in Android P @ I/O Extended Bangkok 2018
 
Griffon Presentation
Griffon PresentationGriffon Presentation
Griffon Presentation
 
Google Wave API: Now and Beyond
Google Wave API: Now and BeyondGoogle Wave API: Now and Beyond
Google Wave API: Now and Beyond
 
Android development
Android developmentAndroid development
Android development
 
Google Web Toolkit
Google Web ToolkitGoogle Web Toolkit
Google Web Toolkit
 
Workshop 26: React Native - The Native Side
Workshop 26: React Native - The Native SideWorkshop 26: React Native - The Native Side
Workshop 26: React Native - The Native Side
 
Java Web Programming on Google Cloud Platform [3/3] : Google Web Toolkit
Java Web Programming on Google Cloud Platform [3/3] : Google Web ToolkitJava Web Programming on Google Cloud Platform [3/3] : Google Web Toolkit
Java Web Programming on Google Cloud Platform [3/3] : Google Web Toolkit
 
[1D1]신개념 N스크린 웹 앱 프레임워크 PARS
[1D1]신개념 N스크린 웹 앱 프레임워크 PARS[1D1]신개념 N스크린 웹 앱 프레임워크 PARS
[1D1]신개념 N스크린 웹 앱 프레임워크 PARS
 
softshake 2014 - Java EE
softshake 2014 - Java EEsoftshake 2014 - Java EE
softshake 2014 - Java EE
 
Android presentation
Android presentationAndroid presentation
Android presentation
 
Android MVVM architecture using Kotlin, Dagger2, LiveData, MediatorLiveData
Android MVVM architecture using Kotlin, Dagger2, LiveData, MediatorLiveDataAndroid MVVM architecture using Kotlin, Dagger2, LiveData, MediatorLiveData
Android MVVM architecture using Kotlin, Dagger2, LiveData, MediatorLiveData
 
Apache Cordova In Action
Apache Cordova In ActionApache Cordova In Action
Apache Cordova In Action
 
Introduction to Things board (An Open Source IoT Cloud Platform)
Introduction to Things board (An Open Source IoT Cloud Platform)Introduction to Things board (An Open Source IoT Cloud Platform)
Introduction to Things board (An Open Source IoT Cloud Platform)
 
Pavlo Zhdanov "Java and Swift: How to Create Applications for Automotive Head...
Pavlo Zhdanov "Java and Swift: How to Create Applications for Automotive Head...Pavlo Zhdanov "Java and Swift: How to Create Applications for Automotive Head...
Pavlo Zhdanov "Java and Swift: How to Create Applications for Automotive Head...
 
Java Advance 4deleteQuery.PNGJava Advance 4deleteQuerySucc.docx
Java Advance 4deleteQuery.PNGJava Advance 4deleteQuerySucc.docxJava Advance 4deleteQuery.PNGJava Advance 4deleteQuerySucc.docx
Java Advance 4deleteQuery.PNGJava Advance 4deleteQuerySucc.docx
 

Mais de Akash Rajguru

Sri monthly presentation 2016
Sri monthly presentation 2016Sri monthly presentation 2016
Sri monthly presentation 2016Akash Rajguru
 
Sri monthly presentation 2015
Sri monthly presentation 2015Sri monthly presentation 2015
Sri monthly presentation 2015Akash Rajguru
 
Final Year presentation
Final Year presentationFinal Year presentation
Final Year presentationAkash Rajguru
 
Akash final-year-project report
Akash final-year-project reportAkash final-year-project report
Akash final-year-project reportAkash Rajguru
 
B.Eng-Final Year Project interim-report
B.Eng-Final Year Project interim-reportB.Eng-Final Year Project interim-report
B.Eng-Final Year Project interim-reportAkash Rajguru
 
Education akash bsit1110
Education akash bsit1110Education akash bsit1110
Education akash bsit1110Akash Rajguru
 

Mais de Akash Rajguru (7)

Sri monthly presentation 2016
Sri monthly presentation 2016Sri monthly presentation 2016
Sri monthly presentation 2016
 
Sri monthly presentation 2015
Sri monthly presentation 2015Sri monthly presentation 2015
Sri monthly presentation 2015
 
Final Year presentation
Final Year presentationFinal Year presentation
Final Year presentation
 
Akash final-year-project report
Akash final-year-project reportAkash final-year-project report
Akash final-year-project report
 
B.Eng-Final Year Project interim-report
B.Eng-Final Year Project interim-reportB.Eng-Final Year Project interim-report
B.Eng-Final Year Project interim-report
 
Project
ProjectProject
Project
 
Education akash bsit1110
Education akash bsit1110Education akash bsit1110
Education akash bsit1110
 

Último

Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseAnaAcapella
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxJisc
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfNirmal Dwivedi
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701bronxfugly43
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxDr. Sarita Anand
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxVishalSingh1417
 
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdfVishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdfssuserdda66b
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 

Último (20)

Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdfVishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 

4th semester project report

  • 1. 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 clientserver 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 modules 1. 2. 3. 4. 5. ClientServer Socket Programming Module. Wifi on off Button . Server Socket & Client Socket android application . Wifi Demo . 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
  • 2. 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
  • 3. Socket Programming Module 1 Socket 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. Class Diagram Deployment Diagram ServerSide.java import java.awt.BorderLayout; import java.awt.Button; import java.awt.Frame; import java.awt.List; import java.awt.TextField; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.BufferedWriter;
  • 4. import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.ServerSocket; import java.net.Socket; import java.io.*; 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);
  • 5. 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){} button1.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub try{ bw.write(text.getText()); bw.newLine(); bw.flush(); text.setText(""); } catch(Exception n){} } }); button2.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub System.exit(0); } }); } public void run() { try { s1.setSoTimeout(1);
  • 6. } catch(Exception e){} while(true) { try { list.addItem(br.readLine()); } catch(Exception h){} } } } Snapshot clinSide.java import java.awt.BorderLayout; import java.awt.Button; import java.awt.Frame; import java.awt.List; import java.awt.TextField;
  • 7. import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.ServerSocket; import java.net.Socket; import java.io.*; 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");
  • 8. 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); else{ try { bw.write(text.getText()); bw.newLine(); bw.flush(); text.setText(""); }catch(Exception m){} } } */ button1.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub
  • 9. try{ bw.write(text.getText()); bw.newLine(); bw.flush(); text.setText(""); } catch(Exception n){} } }); button2.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub System.exit(0); } }); } public void run() { try { s.setSoTimeout(1); } catch(Exception e){} while(true) { try { list.addItem(br.readLine()); } catch(Exception h){} } } }
  • 10. Snapshot Module 2 WiFi On Off button In this module I have worked and learned how to enable and disable a wifi on device by using wifiManager . public class MainActivity extends Activity { //private static final BroadcastReceiver WifiStateChangedReceiver = null; TextView WifiState; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); WifiState = (TextView)findViewById(R.id.wifistate); Button OnWifi = (Button)findViewById(R.id.onwifi); Button OffWifi = (Button)findViewById(R.id.offwifi);
  • 11. this.registerReceiver(this.WifiStateChangedReceiver, new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION)); OnWifi.setOnClickListener(new Button.OnClickListener(){ @Override public void onClick(View v) { // TODO Auto-generated method stub WifiManager wifiManager = (WifiManager)getBaseContext().getSystemService(Context.WIFI_SERVICE); wifiManager.setWifiEnabled(true); }}); OffWifi.setOnClickListener(new Button.OnClickListener(){ @Override public void onClick(View arg0) { // TODO Auto-generated method stub WifiManager wifiManager = (WifiManager)getBaseContext().getSystemService(Context.WIFI_SERVICE); wifiManager.setWifiEnabled(false); }}); } private BroadcastReceiver WifiStateChangedReceiver = new BroadcastReceiver(){ @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub int 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");
  • 13. Module -3: Server Socket & Client Socket in Android Application In 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. Server Socket application code MyServer.java package edu.amplify.serversocket; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.ServerSocket; import java.net.Socket; mport android.os.Handler; import android.os.Message; public class MyServer { Thread m_objThread; ServerSocket m_server; String m_strMessage; DataDisplay m_dataDisplay; Object m_connected; public MyServer() { } public void setEventListener(DataDisplay dataDispaly) { m_dataDisplay= dataDispaly; } public void startListening() { m_objThread= new Thread(new Runnable() { @Override public void run() {
  • 14. // TODO Auto-generated method stub try { m_server=new ServerSocket(2001); Socket connectedSocket = m_server.accept(); Message clientmessage= Message.obtain(); ObjectInputStream ois = new ObjectInputStream(connectedSocket.getInputStream()); String strMessage = (String)ois.readObject(); clientmessage.obj=strMessage; mHandler.sendMessage(clientmessage); ObjectOutputStream oos=new ObjectOutputStream(connectedSocket.getOutputStream()); oos.writeObject("hai...client this is server"); ois.close(); oos.close(); m_server.close(); } catch(Exception e) { Message msg3 = Message.obtain(); msg3.obj=e.getMessage(); mHandler.sendMessage(msg3); } } }); m_objThread.start(); } Handler mHandler = new Handler() { public void handleMessage(Message status){ m_dataDisplay.Display(status.obj.toString()); } }; }
  • 15. DataDisplay.java package edu.amplify.serversocket; public interface DataDisplay { void Display(String message); } MainActivity.java ackage edu.amplify.wifinooff; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.wifi.WifiManager; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.widget.Button; import android.widget.TextView; public class MainActivity extends Activity { //private static final BroadcastReceiver WifiStateChangedReceiver = null; TextView WifiState; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); WifiState = (TextView)findViewById(R.id.wifistate); Button OnWifi = (Button)findViewById(R.id.onwifi); Button OffWifi = (Button)findViewById(R.id.offwifi); this.registerReceiver(this.WifiStateChangedReceiver, new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION)); OnWifi.setOnClickListener(new Button.OnClickListener(){
  • 16. @Override public void onClick(View v) { // TODO Auto-generated method stub WifiManager wifiManager = (WifiManager)getBaseContext().getSystemService(Context.WIFI_SERVICE); wifiManager.setWifiEnabled(true); }}); OffWifi.setOnClickListener(new Button.OnClickListener(){ @Override public void onClick(View arg0) { // TODO Auto-generated method stub WifiManager wifiManager = (WifiManager)getBaseContext().getSystemService(Context.WIFI_SERVICE); wifiManager.setWifiEnabled(false); }}); } private BroadcastReceiver WifiStateChangedReceiver = new BroadcastReceiver(){ @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub int 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");
  • 17. break; case WifiManager.WIFI_STATE_ENABLING: WifiState.setText("WIFI STATE ENABLING"); break; case WifiManager.WIFI_STATE_UNKNOWN: WifiState.setText("WIFI STATE UNKNOWN"); break; } }}; } AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="edu.amplify.serversocket" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /> <uses-permission android:name="android.permission.INTERNET" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="edu.amplify.serversocket.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application>
  • 18. Client Socket application code MainActivity.java package edu.amplify.clintsocket; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import import import import import import import android.os.Bundle; android.os.Handler; android.os.Message; android.app.Activity; android.view.Menu; android.view.View; android.widget.TextView; public class MainActivity extends Activity { TextView serverMessage; Thread m_objThreadClient; Socket clientSocket; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); serverMessage =(TextView)findViewById(R.id.textView1); } public void Start(View view) { m_objThreadClient=new Thread(new Runnable() { public void run() { try { clientSocket= new Socket("127.0.0.1",2001); ObjectOutputStream oos = new ObjectOutputStream(clientSocket.getOutputStream()); oos.writeObject("Hellow Server....this client "); Message serverMessage= Message.obtain(); ObjectInputStream ois =new ObjectInputStream(clientSocket.getInputStream()); String strMessage = (String)ois.readObject(); serverMessage.obj=strMessage; mHandler.sendMessage(serverMessage); oos.close(); ois.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace();
  • 19. } } }); m_objThreadClient.start(); } Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { messageDisplay(msg.obj.toString()); } }; public void messageDisplay(String servermessage) { serverMessage.setText(""+servermessage); } } AndroidMenifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="edu.amplify.clintsocket" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /> <uses-permission android:name="android.permission.INTERNET" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="edu.amplify.clintsocket.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
  • 20. Snapshot for Server Socket Application
  • 21. Snapshot for Client Socket application
  • 22. 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. Wifi Demo source code MainActivity.java package edu.amplify.wifidemo; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.PrintWriter; import java.net.Socket; import java.net.UnknownHostException; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; public class MainActivity extends Activity { private Socket client; private PrintWriter printwriter; private EditText etMsg, etIP, etPort; private Button button; private String messsage; int port = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);
  • 23. etIP = (EditText) findViewById(R.id.editText1); etPort = (EditText) findViewById(R.id.editText2); etMsg = (EditText) findViewById(R.id.editText3); button = (Button) findViewById(R.id.button1); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub messsage = etMsg.getText().toString(); etMsg.setText(""); port = Integer.parseInt(etPort.getText().toString()); new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub try { client = new Socket(etIP.getText().toString(), port); // ObjectOutputStream oos = new ObjectOutputStream(client.getOutputStream()); // oos.writeObject(messsage); printwriter = new PrintWriter(client.getOutputStream()); printwriter.write(messsage); printwriter.flush(); printwriter.close(); client.close(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
  • 24. }).start(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } } AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="edu.amplify.wifidemo" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></usespermission> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></usespermission> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="edu.amplify.wifidemo.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
  • 25. Snapshot for Wifi Demo application
  • 26. Snapshot for Server program running on linux machine
  • 27. 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. Sequence Diagram for wifi direct demo Wifi Direct Demo source code WifiDirectBroadcastReceiver.java package com.example.android.wifidirect; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.net.NetworkInfo; import android.net.wifi.p2p.WifiP2pDevice;
  • 28. import android.net.wifi.p2p.WifiP2pManager; import android.net.wifi.p2p.WifiP2pManager.Channel; import android.net.wifi.p2p.WifiP2pManager.PeerListListener; import android.util.Log; /** * A BroadcastReceiver that notifies of important wifi p2p events. */ public class WiFiDirectBroadcastReceiver extends BroadcastReceiver { private WifiP2pManager manager; private Channel channel; private WiFiDirectActivity activity; /** * @param manager WifiP2pManager system service * @param channel Wifi p2p channel * @param activity activity associated with the receiver */ public WiFiDirectBroadcastReceiver(WifiP2pManager manager, Channel channel, WiFiDirectActivity activity) { super(); this.manager = manager; this.channel = channel; this.activity = activity; } /* * (non-Javadoc) * @see android.content.BroadcastReceiver#onReceive(android.content.Context, * android.content.Intent) */ @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) { // 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);
  • 29. } else { activity.setIsWifiP2pEnabled(false); activity.resetData(); } 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)) { if (manager == null) { return; } NetworkInfo networkInfo = (NetworkInfo) intent .getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO); if (networkInfo.isConnected()) { // we are connected with the other device, request connection // info to find group owner IP DeviceDetailFragment fragment = (DeviceDetailFragment) activity .getFragmentManager().findFragmentById(R.id.frag_detail); manager.requestConnectionInfo(channel, fragment); } else { // It's a disconnect activity.resetData(); } } else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) { DeviceListFragment fragment = (DeviceListFragment) activity.getFragmentManager() .findFragmentById(R.id.frag_list); fragment.updateThisDevice((WifiP2pDevice) intent.getParcelableExtra( WifiP2pManager.EXTRA_WIFI_P2P_DEVICE));
  • 30. } } } DeviceDetailFragment.java package com.example.android.wifidirect; import android.app.Fragment; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.net.wifi.WpsInfo; import android.net.wifi.p2p.WifiP2pConfig; import android.net.wifi.p2p.WifiP2pDevice; import android.net.wifi.p2p.WifiP2pInfo; import android.net.wifi.p2p.WifiP2pManager.ConnectionInfoListener; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.example.android.wifidirect.DeviceListFragment.DeviceActionListener; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; /**
  • 31. * 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 { protected static final int CHOOSE_FILE_RESULT_CODE = 20; private View mContentView = null; private WifiP2pDevice device; private WifiP2pInfo info; ProgressDialog progressDialog = null; @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mContentView = inflater.inflate(R.layout.device_detail, null); mContentView.findViewById(R.id.btn_connect).setOnClickListener(new View.OnClickListener() { // // // // // // // @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);
  • 32. } }); 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
  • 33. 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) {
  • 34. // 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); }
  • 35. /** * A simple server socket that accepts connection and writes some data on * the stream. */ public static class FileServerAsyncTask extends AsyncTask<Void, Void, String> { private Context context; private TextView statusText; /** * @param context * @param statusText */ public FileServerAsyncTask(Context context, View statusText) { this.context = context; this.statusText = (TextView) statusText; } @Override protected String doInBackground(Void... params) { try { ServerSocket serverSocket = new ServerSocket(8988); Log.d(WiFiDirectActivity.TAG, "Server: Socket opened"); Socket client = serverSocket.accept(); Log.d(WiFiDirectActivity.TAG, "Server: connection done"); final File f = new File(Environment.getExternalStorageDirectory() + "/" + context.getPackageName() + "/wifip2pshared-" + System.currentTimeMillis() + ".txt",".jpg"); File dirs = new File(f.getParent()); if (!dirs.exists()) dirs.mkdirs(); f.createNewFile(); Log.d(WiFiDirectActivity.TAG, "server: copying files " + f.toString()); InputStream inputstream = client.getInputStream(); copyFile(inputstream, new FileOutputStream(f)); serverSocket.close(); return f.getAbsolutePath(); } catch (IOException e) { Log.e(WiFiDirectActivity.TAG, e.getMessage());
  • 36. return null; } } /* * (non-Javadoc) * @see android.os.AsyncTask#onPostExecute(java.lang.Object) */ @Override protected void onPostExecute(String result) { if (result != null) { statusText.setText("File copied - " + result); Intent intent = new Intent(); intent.setAction(android.content.Intent.ACTION_VIEW); intent.setDataAndType(Uri.parse("file://" + result), "text/*"); intent.setDataAndType(Uri.parse("file://" + result), "image/*"); context.startActivity(intent); } } /* * (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();
  • 37. 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; } } DeviceListFragment.java package com.example.android.wifidirect; import android.app.Fragment; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.net.wifi.WpsInfo; import android.net.wifi.p2p.WifiP2pConfig; import android.net.wifi.p2p.WifiP2pDevice; import android.net.wifi.p2p.WifiP2pInfo; import android.net.wifi.p2p.WifiP2pManager.ConnectionInfoListener; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.example.android.wifidirect.DeviceListFragment.DeviceActionListener; import java.io.File; import java.io.FileOutputStream;
  • 38. import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; /** * 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 { protected static final int CHOOSE_FILE_RESULT_CODE = 20; private View mContentView = null; private WifiP2pDevice device; private WifiP2pInfo info; ProgressDialog progressDialog = null; @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mContentView = inflater.inflate(R.layout.device_detail, null); mContentView.findViewById(R.id.btn_connect).setOnClickListener(new View.OnClickListener() { // // // @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
  • 39. // // // // 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);
  • 40. } }); 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());
  • 41. // 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);
  • 42. 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> { private Context context; private TextView statusText; /** * @param context * @param statusText */ public FileServerAsyncTask(Context context, View statusText) { this.context = context; this.statusText = (TextView) statusText; } @Override protected String doInBackground(Void... params) { try { ServerSocket serverSocket = new ServerSocket(8988); Log.d(WiFiDirectActivity.TAG, "Server: Socket opened"); Socket client = serverSocket.accept(); Log.d(WiFiDirectActivity.TAG, "Server: connection done"); final File f = new File(Environment.getExternalStorageDirectory() + "/" + context.getPackageName() + "/wifip2pshared-" + System.currentTimeMillis() + ".txt",".jpg"); File dirs = new File(f.getParent()); if (!dirs.exists()) dirs.mkdirs(); f.createNewFile();
  • 43. Log.d(WiFiDirectActivity.TAG, "server: copying files " + f.toString()); InputStream inputstream = client.getInputStream(); copyFile(inputstream, new FileOutputStream(f)); serverSocket.close(); return f.getAbsolutePath(); } catch (IOException e) { Log.e(WiFiDirectActivity.TAG, e.getMessage()); return null; } } /* * (non-Javadoc) * @see android.os.AsyncTask#onPostExecute(java.lang.Object) */ @Override protected void onPostExecute(String result) { if (result != null) { statusText.setText("File copied - " + result); Intent intent = new Intent(); intent.setAction(android.content.Intent.ACTION_VIEW); intent.setDataAndType(Uri.parse("file://" + result), "text/*"); intent.setDataAndType(Uri.parse("file://" + result), "image/*"); context.startActivity(intent); } } /* * (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;
  • 44. 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; } } FileTransferService.java // Copyright 2011 Google Inc. All Rights Reserved. package com.example.android.wifidirect; import android.app.IntentService; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.util.Log; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetSocketAddress; import java.net.Socket; /** * 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
  • 45. */ 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"); } /* * (non-Javadoc) * @see android.app.IntentService#onHandleIntent(android.content.Intent) */ @Override protected void onHandleIntent(Intent intent) { Context context = getApplicationContext(); if (intent.getAction().equals(ACTION_SEND_FILE)) { String fileUri = intent.getExtras().getString(EXTRAS_FILE_PATH); String host = intent.getExtras().getString(EXTRAS_GROUP_OWNER_ADDRESS); Socket socket = new Socket(); int port = intent.getExtras().getInt(EXTRAS_GROUP_OWNER_PORT); try { Log.d(WiFiDirectActivity.TAG, "Opening client socket - "); socket.bind(null); socket.connect((new InetSocketAddress(host, port)), SOCKET_TIMEOUT); Log.d(WiFiDirectActivity.TAG, "Client socket - " + socket.isConnected()); OutputStream stream = socket.getOutputStream(); ContentResolver cr = context.getContentResolver(); InputStream is = null; try { is = cr.openInputStream(Uri.parse(fileUri));
  • 46. } catch (FileNotFoundException e) { Log.d(WiFiDirectActivity.TAG, e.toString()); } DeviceDetailFragment.copyFile(is, stream); Log.d(WiFiDirectActivity.TAG, "Client: Data written"); } catch (IOException e) { Log.e(WiFiDirectActivity.TAG, e.getMessage()); } finally { if (socket != null) { if (socket.isConnected()) { try { socket.close(); } catch (IOException e) { // Give up e.printStackTrace(); } } } } } } } WifiDirectActivity.java package com.example.android.wifidirect; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.wifi.p2p.WifiP2pConfig; import android.net.wifi.p2p.WifiP2pDevice; import android.net.wifi.p2p.WifiP2pManager; import android.net.wifi.p2p.WifiP2pManager.ActionListener; import android.net.wifi.p2p.WifiP2pManager.Channel; import android.net.wifi.p2p.WifiP2pManager.ChannelListener; import android.os.Bundle; import android.provider.Settings; import android.util.Log;
  • 47. import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.Toast; import com.example.android.wifidirect.DeviceListFragment.DeviceActionListener; /** * 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); // add necessary intent values to be matched. intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION); intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
  • 48. intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION); intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION); manager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE); channel = manager.initialize(this, getMainLooper(), null); } /** 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(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.action_items, menu);
  • 49. return true; } /* * (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 onFailure(int reasonCode) {
  • 50. Toast.makeText(WiFiDirectActivity.this, "Discovery Failed : " + reasonCode, Toast.LENGTH_SHORT).show(); } }); return true; default: return super.onOptionsItemSelected(item); } } @Override public void showDetails(WifiP2pDevice device) { DeviceDetailFragment fragment = (DeviceDetailFragment) getFragmentManager() .findFragmentById(R.id.frag_detail); fragment.showDetails(device); } @Override public void connect(WifiP2pConfig config) { manager.connect(channel, config, new ActionListener() { @Override public void onSuccess() { // WiFiDirectBroadcastReceiver will notify us. Ignore for now. } @Override public void onFailure(int reason) { Toast.makeText(WiFiDirectActivity.this, "Connect failed. Retry.", 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() {
  • 51. @Override public void onFailure(int reasonCode) { Log.d(TAG, "Disconnect failed. Reason :" + reasonCode); } @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();
  • 52. } else if (fragment.getDevice().status == WifiP2pDevice.AVAILABLE || fragment.getDevice().status == WifiP2pDevice.INVITED) { manager.cancelConnect(channel, new ActionListener() { @Override public void onSuccess() { Toast.makeText(WiFiDirectActivity.this, "Aborting connection", Toast.LENGTH_SHORT).show(); } @Override public void onFailure(int reasonCode) { Toast.makeText(WiFiDirectActivity.this, "Connect abort request failed. Reason Code: " + reasonCode, Toast.LENGTH_SHORT).show(); } }); } } } } AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.android.wifidirect" android:versionCode="1" android:versionName="1.0"> <uses-sdk android:minSdkVersion="14" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /> <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.READ_PHONE_STATE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <!-- Market filtering --> <uses-feature android:name="android.hardware.wifi.direct" android:required="true"/> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@android:style/Theme.Holo">
  • 53. <activity android:name=".WiFiDirectActivity" android:label="@string/app_name" android:launchMode="singleTask"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <!-- Used for transferring files after a successful connection --> <service android:enabled="true" android:name=".FileTransferService" /> </application> </manifest> Snapshots for Wifi Direct Demo application