I need to create an App that receives and transmit text data from a computer to a Android App. I found this : https://github.com/mik3y/usb-serial-for-android.
I used the example to see if I starting like this I could see a comunication between then, when I used in my mobile it appears 1 device found Vendor 1519 Product 0020 No Driver. It's like not happened the communication and not found the computer.
Here is the code:
SerialConsoleActivity.java--
package com.hoho.android.usbserial.examples;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.ScrollView;
import android.widget.TextView;
import com.hoho.android.usbserial.driver.UsbSerialDriver;
import com.hoho.android.usbserial.util.HexDump;
import com.hoho.android.usbserial.util.SerialInputOutputManager;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Monitors a single {#link UsbSerialDriver} instance, showing all data
* received.
*
* #author mike wakerly (opensource#hoho.com)
*/
public class SerialConsoleActivity extends Activity {
private final String TAG = SerialConsoleActivity.class.getSimpleName();
/**
* Driver instance, passed in statically via
* {#link #show(Context, UsbSerialDriver)}.
*
* <p/>
* This is a devious hack; it'd be cleaner to re-create the driver using
* arguments passed in with the {#link #startActivity(Intent)} intent. We
* can get away with it because both activities will run in the same
* process, and this is a simple demo.
*/
private static UsbSerialDriver sDriver = null;
private TextView mTitleTextView;
private TextView mDumpTextView;
private ScrollView mScrollView;
private final ExecutorService mExecutor = Executors.newSingleThreadExecutor();
private SerialInputOutputManager mSerialIoManager;
private final SerialInputOutputManager.Listener mListener =
new SerialInputOutputManager.Listener() {
#Override
public void onRunError(Exception e) {
Log.d(TAG, "Runner stopped.");
}
#Override
public void onNewData(final byte[] data) {
SerialConsoleActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
SerialConsoleActivity.this.updateReceivedData(data);
}
});
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.serial_console);
mTitleTextView = (TextView) findViewById(R.id.demoTitle);
mDumpTextView = (TextView) findViewById(R.id.consoleText);
mScrollView = (ScrollView) findViewById(R.id.demoScroller);
}
#Override
protected void onPause() {
super.onPause();
stopIoManager();
if (sDriver != null) {
try {
sDriver.close();
} catch (IOException e) {
// Ignore.
}
sDriver = null;
}
finish();
}
#Override
protected void onResume() {
super.onResume();
Log.d(TAG, "Resumed, sDriver=" + sDriver);
if (sDriver == null) {
mTitleTextView.setText("No serial device.");
} else {
try {
sDriver.open();
sDriver.setParameters(115200, 8, UsbSerialDriver.STOPBITS_1, UsbSerialDriver.PARITY_NONE);
} catch (IOException e) {
Log.e(TAG, "Error setting up device: " + e.getMessage(), e);
mTitleTextView.setText("Error opening device: " + e.getMessage());
try {
sDriver.close();
} catch (IOException e2) {
// Ignore.
}
sDriver = null;
return;
}
mTitleTextView.setText("Serial device: " + sDriver.getClass().getSimpleName());
}
onDeviceStateChange();
}
private void stopIoManager() {
if (mSerialIoManager != null) {
Log.i(TAG, "Stopping io manager ..");
mSerialIoManager.stop();
mSerialIoManager = null;
}
}
private void startIoManager() {
if (sDriver != null) {
Log.i(TAG, "Starting io manager ..");
mSerialIoManager = new SerialInputOutputManager(sDriver, mListener);
mExecutor.submit(mSerialIoManager);
}
}
private void onDeviceStateChange() {
stopIoManager();
startIoManager();
}
private void updateReceivedData(byte[] data) {
final String message = "Read " + data.length + " bytes: \n"
+ HexDump.dumpHexString(data) + "\n\n";
mDumpTextView.append(message);
mScrollView.smoothScrollTo(0, mDumpTextView.getBottom());
}
/**
* Starts the activity, using the supplied driver instance.
*
* #param context
* #param driver
*/
static void show(Context context, UsbSerialDriver driver) {
sDriver = driver;
final Intent intent = new Intent(context, SerialConsoleActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NO_HISTORY);
context.startActivity(intent);
}
}
DeviceListActivity--
import android.app.Activity;
import android.content.Context;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.TwoLineListItem;
import com.hoho.android.usbserial.driver.UsbSerialDriver;
import com.hoho.android.usbserial.driver.UsbSerialProber;
import com.hoho.android.usbserial.util.HexDump;
import java.util.ArrayList;
import java.util.List;
/**
* Shows a {#link ListView} of available USB devices.
*
* #author mike wakerly (opensource#hoho.com)
*/
public class DeviceListActivity extends Activity {
private final String TAG = DeviceListActivity.class.getSimpleName();
private UsbManager mUsbManager;
private ListView mListView;
private TextView mProgressBarTitle;
private ProgressBar mProgressBar;
private static final int MESSAGE_REFRESH = 101;
private static final long REFRESH_TIMEOUT_MILLIS = 5000;
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_REFRESH:
refreshDeviceList();
mHandler.sendEmptyMessageDelayed(MESSAGE_REFRESH, REFRESH_TIMEOUT_MILLIS);
break;
default:
super.handleMessage(msg);
break;
}
}
};
/** Simple container for a UsbDevice and its driver. */
private static class DeviceEntry {
public UsbDevice device;
public UsbSerialDriver driver;
DeviceEntry(UsbDevice device, UsbSerialDriver driver) {
this.device = device;
this.driver = driver;
}
}
private List<DeviceEntry> mEntries = new ArrayList<DeviceEntry>();
private ArrayAdapter<DeviceEntry> mAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
mListView = (ListView) findViewById(R.id.deviceList);
mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
mProgressBarTitle = (TextView) findViewById(R.id.progressBarTitle);
mAdapter = new ArrayAdapter<DeviceEntry>(this, android.R.layout.simple_expandable_list_item_2, mEntries) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final TwoLineListItem row;
if (convertView == null){
final LayoutInflater inflater =
(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = (TwoLineListItem) inflater.inflate(android.R.layout.simple_list_item_2, null);
} else {
row = (TwoLineListItem) convertView;
}
final DeviceEntry entry = mEntries.get(position);
final String title = String.format("Vendor %s Product %s",
HexDump.toHexString((short) entry.device.getVendorId()),
HexDump.toHexString((short) entry.device.getProductId()));
row.getText1().setText(title);
final String subtitle = entry.driver != null ?
entry.driver.getClass().getSimpleName() : "No Driver";
row.getText2().setText(subtitle);
return row;
}
};
mListView.setAdapter(mAdapter);
mListView.setOnItemClickListener(new ListView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d(TAG, "Pressed item " + position);
if (position >= mEntries.size()) {
Log.w(TAG, "Illegal position.");
return;
}
final DeviceEntry entry = mEntries.get(position);
final UsbSerialDriver driver = entry.driver;
if (driver == null) {
Log.d(TAG, "No driver.");
return;
}
showConsoleActivity(driver);
}
});
}
#Override
protected void onResume() {
super.onResume();
mHandler.sendEmptyMessage(MESSAGE_REFRESH);
}
#Override
protected void onPause() {
super.onPause();
mHandler.removeMessages(MESSAGE_REFRESH);
}
private void refreshDeviceList() {
showProgressBar();
new AsyncTask<Void, Void, List<DeviceEntry>>() {
#Override
protected List<DeviceEntry> doInBackground(Void... params) {
Log.d(TAG, "Refreshing device list ...");
SystemClock.sleep(1000);
final List<DeviceEntry> result = new ArrayList<DeviceEntry>();
for (final UsbDevice device : mUsbManager.getDeviceList().values()) {
final List<UsbSerialDriver> drivers =
UsbSerialProber.probeSingleDevice(mUsbManager, device);
Log.d(TAG, "Found usb device: " + device);
if (drivers.isEmpty()) {
Log.d(TAG, " - No UsbSerialDriver available.");
result.add(new DeviceEntry(device, null));
} else {
for (UsbSerialDriver driver : drivers) {
Log.d(TAG, " + " + driver);
result.add(new DeviceEntry(device, driver));
}
}
}
return result;
}
#Override
protected void onPostExecute(List<DeviceEntry> result) {
mEntries.clear();
mEntries.addAll(result);
mAdapter.notifyDataSetChanged();
mProgressBarTitle.setText(
String.format("%s device(s) found",Integer.valueOf(mEntries.size())));
hideProgressBar();
Log.d(TAG, "Done refreshing, " + mEntries.size() + " entries found.");
}
}.execute((Void) null);
}
private void showProgressBar() {
mProgressBar.setVisibility(View.VISIBLE);
mProgressBarTitle.setText(R.string.refreshing);
}
private void hideProgressBar() {
mProgressBar.setVisibility(View.INVISIBLE);
}
private void showConsoleActivity(UsbSerialDriver driver) {
SerialConsoleActivity.show(this, driver);
}
}
Have you installed the driver your phone migh require to work? For example any Samsung smartphone will require the Key-software to be installed in order for the drivers to function properly. I am asuming you want to try USB-debugging, correct?
It seems that you don't have the right driver installed for your device.Try firstly to use google official tools for android development like adb and friends. If they don't work than you don't have the driver. Visit the site of the vendor of your mobile phone and download it.
It seems that you lack of USB driver.The driver should be download at http://www.ftdichip.com/Drivers/VCP.htm
according to you system version. The same problem confused me, and that driver solves this problem. Hope it works for you.
Related
Hello I have problem with delay in stream video on android.
I have a delay of about 8 seconds and it is very annoying. There is no delay on the computer.
This is a stream from camera like gopro via wifi --> rtsp.
I found this topic on SO...
Streaming videos on VideoView
And I have the same problem as Akeshwar Jha. Unfortunately, I don't know Java. Could someone help me modify the design according to what Akeshwar Jha gave ??
package com.teststream.robotclient;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.util.Pair;
import android.widget.VideoView;
import com.jmedeisis.bugstick.Joystick;
import com.jmedeisis.bugstick.JoystickListener;
public class MainActivity extends Activity {
private String host;
private int port;
private DatagramSocket socket;
private VideoView videoView;
private static final String TAG = "MainActivity";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
WifiInfo info = wifiManager.getConnectionInfo();
String ssid = info.getSSID();
String desiredSsid = getString(R.string.ssid);
Log.i(TAG, desiredSsid);
if(!ssid.equals(desiredSsid) && !desiredSsid.equals("*")) {
exitDialog("Wrong SSID", "The SSID of the WIFI network is wrong. Desired SSID: " + desiredSsid);
}
host = getString(R.string.host);
port = Integer.parseInt(getString(R.string.port));
//new CheckConnectivity().execute();
videoView = findViewById(R.id.videoView);
Uri videoUri = Uri.parse(getString(R.string.video_uri));
videoView.setVideoURI(videoUri);
videoView.start();
Joystick left = findViewById(R.id.joystick_left);
Joystick right = findViewById(R.id.joystick_right);
left.setJoystickListener(new JoystickListener() {
#Override
public void onDown() {
log("down");
}
#Override
public void onDrag(float degrees, float offset) {
log("deg: " + degrees + ", off: " + offset);
float upValue = (float) Math.sin(Math.toRadians(degrees)) * offset;
log("" + upValue);
int intValue = normalisedFloatToByte(upValue);
new UpdateServo().execute(Pair.create(0xff, intValue));
}
#Override
public void onUp() {
log("up");
}
});
right.setJoystickListener(new JoystickListener() {
#Override
public void onDown() {
log("down");
}
#Override
public void onDrag(float degrees, float offset) {
log("deg: " + degrees + ", off: " + offset);
float upValue = (float) Math.sin(Math.toRadians(degrees)) * offset;
log("" + upValue);
int intValue = normalisedFloatToByte(upValue);
new UpdateServo().execute(Pair.create(0xfe, intValue));
}
#Override
public void onUp() {
log("up");
}
});
}
private int normalisedFloatToByte(float value) {
if(value < -1.0 || value > 1.0) {
return 0;
}
return 127 + Math.round(value * 127);
}
private void log(String text) {
Log.d(TAG, text);
}
private void exitDialog(String title, String text) {
new AlertDialog.Builder(MainActivity.this)
.setTitle(title)
.setMessage(text)
.setNeutralButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
})
.show();
}
class CheckConnectivity extends AsyncTask<Void, Void, Boolean> {
protected Boolean doInBackground(Void ...params) {
try {
if(!InetAddress.getByName(host).isReachable(2000)) {
return false;
}
} catch (UnknownHostException e) {
return false;
} catch (IOException e) {
return false;
}
return true;
}
protected void onPostExecute(Boolean result) {
if(result == false) {
exitDialog("Can't connect", "Can't connect with host " + host);
}
}
}
class UpdateServo extends AsyncTask<Pair<Integer, Integer>, Void, Void> {
protected Void doInBackground(Pair<Integer, Integer>... requests) {
byte[] payload = {
requests[0].first.byteValue(),
requests[0].second.byteValue()
};
try {
InetAddress addr = InetAddress.getByName(host);
DatagramPacket sendPacket = new DatagramPacket(payload, 0, payload.length, addr, port);
if (socket != null) {
socket.disconnect();
socket.close();
}
socket = new DatagramSocket(port);
socket.send(sendPacket);
} catch (UnknownHostException e) {
Log.e(TAG, "getByName failed");
} catch (IOException e) {
Log.e(TAG, "send failed");
}
return null;
}
}
#Override
public void onDestroy() {
super.onDestroy();
}
}
Thank you in advance for your help.
Hello iam stuck in problem since yesterday searched everything anywhere i create application which show device which arre connected to same router wifi , then iam able to connect both device using this exmple
https://developer.android.com/guide/topics/connectivity/wifip2p.html#creating-app
everything is okay both devices are connected but when transfer file serviceintent is not starting so thats why i cant transfer anything , there is not log error but happend nothing when i choose image to send
MainActivity Class
package com.b.wifip2p;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.WpsInfo;
import android.net.wifi.p2p.WifiP2pConfig;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pDeviceList;
import android.net.wifi.p2p.WifiP2pGroup;
import android.net.wifi.p2p.WifiP2pInfo;
import android.net.wifi.p2p.WifiP2pManager;
import android.os.AsyncTask;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.format.Formatter;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.SQLOutput;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class MainActivity extends AppCompatActivity implements WifiP2pManager.PeerListListener, WifiP2pManager.ConnectionInfoListener {
Button button;
private boolean isWifiP2pEnabled = false;
private boolean retryChannel = false;
private final IntentFilter intentFilter = new IntentFilter();
private WifiP2pManager.Channel channel;
WifiP2pManager.Channel mChannel = null;
WifiP2pManager mManager;
private WifiP2pInfo info;
BroadCast broadCast;
private BroadcastReceiver receiver = null;
static List peers = new ArrayList();
ListView lv;
static Adapater myadapter;
ArrayList<DeviceInfo_Bean>list=new ArrayList<>();
private WifiP2pDevice device;
String hostaddd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv=findViewById(R.id.lv);
myadapter=new Adapater(this,list);
button=findViewById(R.id.button);
lv.setAdapter(myadapter);
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);
mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
mChannel = mManager.initialize(this, getMainLooper(), null);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
connect();
}
});
mManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
System.out.println("---sucess discover");
}
#Override
public void onFailure(int reasonCode) {
System.out.println("---fail");
}
});
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, 007);
WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ipAddress = wifiInfo.getIpAddress();
System.out.println("---ip"+ipAddress);
}
});
}
#Override
public void onResume() {
super.onResume();
broadCast = new BroadCast(mManager, mChannel, MainActivity.this);
registerReceiver(broadCast, intentFilter);
}
#Override
public void onPause() {
super.onPause();
unregisterReceiver(broadCast);
}
private static WifiP2pManager.PeerListListener peerListListener = new WifiP2pManager.PeerListListener() {
#Override
public void
onPeersAvailable(WifiP2pDeviceList peerList) {
List<WifiP2pDevice> refreshedPeers = (List<WifiP2pDevice>) peerList.getDeviceList();
if (!refreshedPeers.equals(peers)) {
peers.clear();
peers.addAll(refreshedPeers);
System.out.println("---ref"+refreshedPeers);
}
if (peers.size() == 0) {
Log.d("-----deviceno", "No devices found");
return;
}
}
};
#Override
public void onPeersAvailable(WifiP2pDeviceList peers) {
for (WifiP2pDevice device : peers.getDeviceList())
{
list.clear();
String address=device.deviceAddress;
String name=device.deviceName;
System.out.println("---name"+name+address);
list.add(new DeviceInfo_Bean(name,address));
}
myadapter.notifyDataSetChanged();
Log.i("----", "Found some peers!!! " + peers.getDeviceList());
}
public void connect() {
DeviceInfo_Bean device = list.get(0);
WifiP2pConfig config = new WifiP2pConfig();
config.deviceAddress = device.address;
config.wps.setup = WpsInfo.PBC;
System.out.println("device in"+device.address);
mManager.connect(mChannel, config, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
Toast.makeText(MainActivity.this, "Connected.",
Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(int reason) {
Toast.makeText(MainActivity.this, "Connect failed. Retry.",
Toast.LENGTH_SHORT).show();
}
});
}
#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(MainActivity.this, 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);
startService(serviceIntent);
}
#Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
public static class FileServerAsyncTask extends AsyncTask<Void, Void, String> {
private Context context;
//private TextView statusText;
/**
* #param context
*
*/
public FileServerAsyncTask(Context context) {
this.context = context;
//this.statusText = (TextView) statusText;
}
#Override
protected String doInBackground(Void... params) {
try {
ServerSocket serverSocket = new ServerSocket(8988);
System.out.println("---socket");
Socket client = serverSocket.accept();
///Log.d(WiFiDirectActivity.TAG, "Server: connection done");
final File f = new File(Environment.getExternalStorageDirectory() + "/"
+ context.getPackageName() + "/wifip2pshared-" + System.currentTimeMillis()
+ ".jpg");
File dirs = new File(f.getParent());
if (!dirs.exists())
dirs.mkdirs();
f.createNewFile();
//Log.d(WiFiDirectActivity.TAG, "server: copying files " + f.toString());
OutputStream stream = client.getOutputStream();
String s="---mymsg";
stream.write(s.getBytes());
Log.e("hello","context value "+context);
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), "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;
}
public void onConnectionInfoAvailable(final WifiP2pInfo info) {
System.out.println("---info");
this.info=info;
// view.setText("Group Owner IP - " + info.groupOwnerAddress.getHostAddress());
InetAddress groupOwnerAddress = info.groupOwnerAddress;
System.out.println("--g"+groupOwnerAddress);
System.out.println("--info"+info.groupOwnerAddress.getHostAddress());
if (info.groupFormed && info.isGroupOwner) {
new FileServerAsyncTask(getApplication())
.execute();
} else if (info.groupFormed) {
// The other device acts as the client. In this case, we enable the
// get file button.
}
// hide the connect button
// mContentView.findViewById(R.id.btn_connect).setVisibility(View.GONE);
}
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());
System.out.println("---device"+device.deviceAddress);
}
}'
Broadcast
package com.b.wifip2p;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.NetworkInfo;
import android.net.wifi.p2p.WifiP2pConfig;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pDeviceList;
import android.net.wifi.p2p.WifiP2pManager;
import android.util.Log;
import android.net.wifi.p2p.WifiP2pManager.PeerListListener;
import java.nio.channels.Channel;
/**
* Created by BHM on 3/3/2018.
*/
public class BroadCast extends BroadcastReceiver {
private WifiP2pManager mManager;
private WifiP2pManager.Channel mChannel;
private MainActivity activity;
PeerListListener peerListListener=null;
public BroadCast(WifiP2pManager manager, WifiP2pManager.Channel channel,
MainActivity activity) {
super();
this.mManager = manager;
this.mChannel = channel;
this.activity = (MainActivity) activity;
}
#Override
public void onReceive(Context context, Intent intent) {
System.out.println("-----broadcast");
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 (mManager != null) {
// mManager.requestPeers(mChannel, (PeerListListener) mChannel);
}
// Log.d(WiFiDirectActivity.TAG, "P2P peers changed");
} else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
if (mManager == 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
mManager.requestConnectionInfo(mChannel, activity);
} 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));
intent.getParcelableExtra(
WifiP2pManager.EXTRA_WIFI_P2P_DEVICE);
}
}
}
FileTransferService here intent is not coming
package com.b.wifip2p;
import android.app.IntentService;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.util.Log;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
/**
* Created by BHM on 3/4/2018.
*/
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);
}
#Override
protected void onHandleIntent(Intent intent) {
System.out.println("--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());
}
MainActivity.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();
}
}
}
}
}
}
}
I know this is a slightly old question by now, but for those looking for answers:
I would recommend checking that you have the intent filters properly in your AndroidManifest.xml file.
It should look something like:
<activity android:name="ShareActivity">
<intent-filter>
<action android:name="android.intent.action.ACTION_SEND_FILE"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="text/plain"/>
</intent-filter>
</activity>
Hey guys ive been working on a project to create a type of wifi hot spot manager, so that it records the connected devices with mac address, ip address and other information. However i can't seem to work out as to why when i press get Clients from screen it doesn't gather any data of whos connected. I have compiled the file to an APK to test on my phone seeing as wifi functionality does not work on the emulator in android studio.
Credit for the code goes to:
1) Android 2.3 wifi hotspot API
2) https://www.whitebyte.info/android/android-wifi-hotspot-manager-class
package com.example.gavin.wifiattendance;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.nfc.Tag;
import android.os.AsyncTask;
import android.util.Log;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import java.util.logging.LogRecord;
import android.os.Handler;
/**
* Created by Gavins on 05/03/2015.
*/
public class AccessPoint extends Activity {
private static int constant = 0;
private Context context;
private static int WIFI_STATE_UNKNOWN = -1;
private static int WIFI_STATE_DISABLING = 0;
private static int WIFI_STATE_DISABLED = 1;
public static int WIFI_STATE_ENABLING = 2;
public static int WIFI_STATE_ENABLED = 3;
private static int WIFI_STATE_FAILED = 4;
final static String[] WIFI_STATE_TEXTSTATE = new String[]{
"DISABLING","DISABLED","ENABLING","ENABLED","FAILED"
};
private WifiManager wifi;
private String TAG = "WifiAP";
private int stateWifi = -1;
private boolean alwaysEnabledWifi = true;
//enable or disable the wifi
public void toggleWifiAP(WifiManager wifiHandler, Context context){
if (wifi == null){
wifi = wifiHandler;
}
boolean wifiApIsOn = getWifiApState() == WIFI_STATE_ENABLED || getWifiApState()==WIFI_STATE_ENABLING;
new SetWifiApTask(!wifiApIsOn, false, context).execute();
}
private int setWifiApEnabled(boolean enabled){
Log.d(TAG, "Set wifi enabled called" + enabled);
WifiConfiguration config = new WifiConfiguration();
config.SSID = "Attend Lecture";
config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
//remember wireless state
if (enabled && stateWifi == -1){
stateWifi = wifi.getWifiState();
}
//disable the wireless
if (enabled && wifi.getConnectionInfo() !=null){
Log.d(TAG, "disable wifi: calling");
wifi.setWifiEnabled(false);
int loopMax = 10;
while (loopMax > 0 && wifi.getWifiState() != WifiManager.WIFI_STATE_DISABLED){
Log.d(TAG, "Disable Wifi: Waiting, pass:" + (10-loopMax));
try{
Thread.sleep(500);
loopMax--;
}catch (Exception e){
e.printStackTrace();
}
}
Log.d(TAG, "Disabling wifi is done, pass: " + (10-loopMax));
}
//enable and disable wifi AP
int state = WIFI_STATE_UNKNOWN;
try {
Log.d(TAG, (enabled?"enabling":"Disabling")+"wifi ap: calling");
wifi.setWifiEnabled(false);
Method method1 = wifi.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
method1.invoke(wifi, config, enabled);
Method method2 = wifi.getClass().getMethod("getWifiState");
state = (Integer)method2.invoke(wifi);
}catch (Exception e){
//Log.e(WIFI_SERVICE, e.getMessage());
}
//Use thread while processing occurs
if (!enabled){
int loopMax = 10;
while (loopMax>0 && (getWifiApState()==WIFI_STATE_DISABLING || getWifiApState()==WIFI_STATE_ENABLED || getWifiApState()==WIFI_STATE_FAILED)){
Log.d(TAG, (enabled?"enabling": "disabling")+ "wifi AP: waiting, pass:" + (10-loopMax));
try {
Thread.sleep(500);
loopMax--;
}catch (Exception e){
}
}
Log.d(TAG, (enabled?"enabling":"disabling")+" Wifi ap: done, pass: " + (10-loopMax));
//enable the wifi
if (stateWifi==WifiManager.WIFI_STATE_ENABLED || stateWifi==WifiManager.WIFI_STATE_ENABLING || stateWifi==WifiManager.WIFI_STATE_UNKNOWN || alwaysEnabledWifi){
Log.d(TAG, "enable wifi: Calling");
wifi.setWifiEnabled(true);
//this way it doesnt hold things up and waits for it to get enabled
}
stateWifi = -1;
}else if (enabled){
int loopMax = 10;
while (loopMax>0 && (getWifiApState()==WIFI_STATE_ENABLING || getWifiApState()==WIFI_STATE_DISABLED || getWifiApState()==WIFI_STATE_FAILED)){
Log.d(TAG, (enabled?"Enabling": "disabling") + "wifi ap: waiting, pass: " + (10-loopMax));
try{
Thread.sleep(500);
loopMax--;
}catch (Exception e){
}
}
Log.d(TAG, (enabled?"Enabling": "disabling")+ "wifi ap: done, pass: " + (10-loopMax));
}
return state;
}
//Get the wifi AP state
public int getWifiApState(){
int state = WIFI_STATE_UNKNOWN;
try {
Method method2 = wifi.getClass().getMethod("getWifiApState");
state = (Integer) method2.invoke(wifi);
}catch (Exception e){
}
if (state>=10){
constant=10;
}
WIFI_STATE_DISABLING = 0+constant;
WIFI_STATE_DISABLED = 1+constant;
WIFI_STATE_ENABLING = 2+constant;
WIFI_STATE_ENABLED = 3+constant;
WIFI_STATE_FAILED = 4+constant;
Log.d(TAG, "getWifiApState " + (state==-1?"UNKNOWN":WIFI_STATE_TEXTSTATE[state-constant]));
return state;
}
class SetWifiApTask extends AsyncTask<Void, Void, Void>{
boolean mMode;
boolean mFinish;
ProgressDialog pDialog;
public SetWifiApTask(boolean mode, boolean finish, Context context){
mMode = mode;
mFinish = finish;
pDialog = new ProgressDialog(context);
}
#Override
protected void onPreExecute(){
super.onPreExecute();
pDialog.setTitle("Turning on Access Point " + (mMode?"On":"Off" + "..."));
pDialog.setMessage("Please wait a moment...");
pDialog.show();
}
#Override
protected void onPostExecute(Void aVoid){
super.onPostExecute(aVoid);
try {
pDialog.dismiss();
MainActivity.updateStatusDisplay();
}catch (IllegalArgumentException e){
};
if (mFinish){
finish();
}
}
#Override
protected Void doInBackground(Void... params) {
setWifiApEnabled(mMode);
return null;
}
}
//get the list connected to the wifi hotspot
public void getClientList(boolean onlyReachable, FinishScanListener finishListener){
getClientList(onlyReachable, 300, finishListener);
}
public void getClientList(final boolean onlyReachable, final int reachableTimeout, final FinishScanListener finishListener){
Runnable runnable = new Runnable() {
#Override
public void run() {
BufferedReader br = null;
final ArrayList<ClientScanResult> result = new ArrayList<>();
try {
br = new BufferedReader(new FileReader("/proc/net/arp"));
String line;
while ((line = br.readLine()) != null){
String[] splitted = line.split(" +");
if ((splitted !=null) && (splitted.length >=4)){
String mac = splitted[3];
if (mac.matches("..:..:..:..:..:..")){
boolean isReachable = InetAddress.getByName(splitted[0]).isReachable(reachableTimeout);
if (!onlyReachable || isReachable){
result.add(new ClientScanResult(splitted[0], splitted[3], splitted[5], isReachable));
}
}
}
}
}catch (Exception e){
Log.e(this.getClass().toString(), e.toString());
}finally {
try {
br.close();
}catch (IOException e){
Log.e(this.getClass().toString(), e.getMessage());
}
}
//Get handler that will be used to post to main thread
Handler mainHandler = new Handler(context.getMainLooper());
Runnable myRunnable = new Runnable() {
#Override
public void run() {
finishListener.onFinishScan(result);
}
};
mainHandler.post(myRunnable);
}
};
Thread myThread = new Thread(runnable);
myThread.start();
}
}
and here is the main activity file:
package com.example.gavin.wifiattendance;
import android.app.Activity;
import android.content.Context;
import android.net.wifi.WifiManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import com.example.gavin.wifiattendance.AccessPoint;
import java.util.ArrayList;
public class MainActivity extends ActionBarActivity{
boolean wasApEnabled = false;
static AccessPoint wifiAP;
private WifiManager wifi;
static Button apButton;
static TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
apButton = (Button) findViewById(R.id.toggleBtn);
textView = (TextView) findViewById(R.id.wifiClients);
wifiAP = new AccessPoint();
wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
scan();
apButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
wifiAP.toggleWifiAP(wifi, MainActivity.this);
}
});
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD|WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON|WindowManager.LayoutParams.FLAG_DIM_BEHIND);
}
public void scan(){
wifiAP.getClientList(false, new FinishScanListener() {
#Override
public void onFinishScan(final ArrayList<ClientScanResult> clients) {
textView.setText("WifiApState:" + wifiAP.getWifiApState()+ "\n\n");
textView.append("Clients: \n");
for (ClientScanResult clientScanResult : clients){
textView.append("====================\n");
textView.append("ipAddress: " + clientScanResult.getIpAddress() + "\n");
textView.append("Device: " + clientScanResult.getDevice() + "\n");
textView.append("macAddress: " + clientScanResult.getMacAddress() + "\n");
textView.append("isReachable: " + clientScanResult.isReachable() + "\n");
}
}
});
}
#Override
public void onResume() {
super.onResume();
if (wasApEnabled) {
if (wifiAP.getWifiApState() != wifiAP.WIFI_STATE_ENABLED && wifiAP.getWifiApState() != wifiAP.WIFI_STATE_ENABLING) {
wifiAP.toggleWifiAP(wifi, MainActivity.this);
}
}
updateStatusDisplay();
}
#Override
public void onPause() {
super.onPause();
boolean wifiApIsOn = wifiAP.getWifiApState()==wifiAP.WIFI_STATE_ENABLED || wifiAP.getWifiApState()==wifiAP.WIFI_STATE_ENABLING;
if (wifiApIsOn){
wasApEnabled = true;
wifiAP.toggleWifiAP(wifi, MainActivity.this);
}else {
wasApEnabled = false;
}
updateStatusDisplay();
}
public static void updateStatusDisplay(){
if (wifiAP.getWifiApState()==wifiAP.WIFI_STATE_ENABLED || wifiAP.getWifiApState()==wifiAP.WIFI_STATE_ENABLING){
apButton.setText("Turn Off");
}else {
apButton.setText("Turn on");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0,0,0, "Get Clients");
return super.onCreateOptionsMenu(menu);
}
public boolean onOptionsItemSelected(int featureId, MenuItem item) {
switch (item.getItemId()){
case 0:
scan();
break;
}
return super.onMenuItemSelected(featureId, item);
}
}
Edit: commented out the main looper made it work but after taking out the comments, the application now crashes on launch
http://gyazo.com/fa068fd1fce3f27f43185c0cd12568c1
I'm working on adding discovery to our app using (http://jmdns.sourceforge.net/). It's actually working correctly on my small home network. But it fails on the large network at the office. I seem to recall reading that if an app blocks for more than 5 seconds that it get's reset. And that appears to be what's happening. But first, how can I be sure that's actually the problem?
Of course, my main question is how can I can make JmDNS work on a large network. And the more general question is what do you do when you need more than 5 seconds?
Small snippet of my code (it's in an AsyncTask):
InetAddress bindingAddress = InetAddress.getByName(ipOfThisDevice);
jmdns = JmDNS.create(bindingAddress);
serviceList = Arrays.asList(jmdns.list("_myappname._tcp.local.",5000)); // 5 second timeout
Here is the code I used in my Android app which you say seems to work at your office?
/*
ZeroConf Browser - http://melloware.com/
Copyright (C) 2010 Melloware Inc
All Rights Reserved.
*/
package com.melloware.zeroconf;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.TreeMap;
import javax.jmdns.JmDNS;
import javax.jmdns.ServiceEvent;
import javax.jmdns.ServiceInfo;
import javax.jmdns.ServiceListener;
import javax.jmdns.ServiceTypeListener;
import android.app.ExpandableListActivity;
import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.MulticastLock;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageView;
import android.widget.TextView;
/**
* Service tab which contains the expandable list of DNS Services and the details of each service type as they are
* gathered.
* <p>
* Copyright (c) 2010 Melloware, Inc. <http://www.melloware.com>
* #author Emil A. Lefkof III <info#melloware.com>
* #version 1.0
*/
public class ServiceActivity extends ExpandableListActivity implements ServiceListener, ServiceTypeListener {
/**
* Tag used for logging
*/
private static final String TAG = ServiceActivity.class.getName();
/**
* Value used to identify in ZeroConf
*/
private static final String HOSTNAME = "melloware";
/**
* Sorted array of top level items which are the Service Types
*/
public static final ArrayList<ServiceType> GROUPS = new ArrayList<ServiceType>();
/**
* Sorted list of the details for each service type
*/
public static final TreeMap<String, ArrayList<ServiceInfo>> DETAILS = new TreeMap<String, ArrayList<ServiceInfo>>();
/**
* Instance of Bonjour/Rendezvous/ZeroConf handler
*/
public static JmDNS jmdns = null;
/**
* Allows an application to receive Wifi Multicast packets.
*/
private static MulticastLock multicastLock = null;
/**
* The backing adapter for the ListView of services
*/
private static DNSExpandableListAdapter mAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAdapter = new DNSExpandableListAdapter();
setListAdapter(mAdapter);
}
/*
* (non-Javadoc)
* #see android.app.Activity#onStart()
*/
#Override
protected void onStart() {
Log.i(TAG, "Starting ServiceActivity...");
super.onStart();
try {
Log.i(TAG, "Starting Mutlicast Lock...");
WifiManager wifi = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
// get the device ip address
final InetAddress deviceIpAddress = getDeviceIpAddress(wifi);
multicastLock = wifi.createMulticastLock(getClass().getName());
multicastLock.setReferenceCounted(true);
multicastLock.acquire();
Log.i(TAG, "Starting ZeroConf probe....");
jmdns = JmDNS.create(deviceIpAddress, HOSTNAME);
jmdns.addServiceTypeListener(this);
} catch (IOException ex) {
Log.e(TAG, ex.getMessage(), ex);
}
Log.i(TAG, "Started ZeroConf probe....");
}
/*
* (non-Javadoc)
* #see android.app.ActivityGroup#onStop()
*/
#Override
protected void onStop() {
Log.i(TAG, "Stopping ServiceActivity...");
super.onStop();
stopScan();
DETAILS.clear();
GROUPS.clear();
if (!isFinishing()) {
mAdapter.notifyDataSetChanged();
}
}
/**
* Stops scanning and cleans up locks.
*/
private static void stopScan() {
try {
if (jmdns != null) {
Log.i(TAG, "Stopping ZeroConf probe....");
jmdns.unregisterAllServices();
jmdns.close();
jmdns = null;
}
if (multicastLock != null) {
Log.i(TAG, "Releasing Mutlicast Lock...");
multicastLock.release();
multicastLock = null;
}
} catch (Exception ex) {
Log.e(TAG, ex.getMessage(), ex);
}
}
/**
* Gets the current Android device IP address or return 10.0.0.2 which is localhost on Android.
* <p>
* #return the InetAddress of this Android device
*/
private InetAddress getDeviceIpAddress(WifiManager wifi) {
InetAddress result = null;
try {
// default to Android localhost
result = InetAddress.getByName("10.0.0.2");
// figure out our wifi address, otherwise bail
WifiInfo wifiinfo = wifi.getConnectionInfo();
int intaddr = wifiinfo.getIpAddress();
byte[] byteaddr = new byte[] { (byte) (intaddr & 0xff), (byte) (intaddr >> 8 & 0xff), (byte) (intaddr >> 16 & 0xff), (byte) (intaddr >> 24 & 0xff) };
result = InetAddress.getByAddress(byteaddr);
} catch (UnknownHostException ex) {
Log.w(TAG, String.format("getDeviceIpAddress Error: %s", ex.getMessage()));
}
return result;
}
/**
* Delegate method from mDNS when a service is added.
*/
public void serviceAdded(ServiceEvent event) {
Log.i(TAG, String.format("ZeroConf serviceAdded(event=\n%s\n)", event.toString()));
ArrayList<ServiceInfo> list = DETAILS.get(event.getType());
if (list != null) {
ServiceInfo info = event.getInfo();
if (!list.contains(info)) {
list.add(info);
}
}
}
/**
* Delegate method from mDNS when a service is removed.
*/
public void serviceRemoved(ServiceEvent event) {
Log.w(TAG, String.format("ZeroConf serviceRemoved(event=\n%s\n)", event.toString()));
}
/**
* Delegate method from mDNS when a service is resolved.
*/
public void serviceResolved(ServiceEvent event) {
Log.i(TAG, String.format("ZeroConf serviceResolved(event=\n%s\n)", event.toString()));
ArrayList<ServiceInfo> list = DETAILS.get(event.getType());
if (list != null) {
ServiceInfo info = event.getInfo();
if (!list.contains(info)) {
list.add(info);
}
}
}
/**
* Delegate method from mDNS when a new service type is discovered.
*/
public void serviceTypeAdded(final ServiceEvent event) {
Log.i(TAG, String.format("ZeroConf serviceTypeAdded(event=\n%s\n)", event.toString()));
jmdns.addServiceListener(event.getType(), this);
runOnUiThread(new Runnable() {
public void run() {
final ServiceType type = new ServiceType();
type.setName(event.getType());
GROUPS.add(type);
Collections.sort(GROUPS);
DETAILS.put(event.getType(), new ArrayList<ServiceInfo>());
mAdapter.notifyDataSetChanged();
}
});
}
/**
* Delegate method from mDNS when a subtype is discovered.
*/
public void subTypeForServiceTypeAdded(ServiceEvent event) {
Log.i(TAG, String.format("ZeroConf subTypeForServiceTypeAdded(event=\n%s\n)", event.toString()));
}
/**
* When a scan is complete show a message if no services found.
* <p>
* #param context the ApplicationContext
*/
public static void scanFinished(Context context) {
if (GROUPS.size() == 0) {
final ServiceType type = new ServiceType();
type.setName(context.getResources().getString(R.string.msg_noservices));
GROUPS.add(type);
mAdapter.notifyDataSetChanged();
stopScan();
}
}
/**
* ExpandableListAdapter that displays the Service Types as groups and when each Service Type is expanded displays a
* list of all discovered Services for that Service Type.
*/
public class DNSExpandableListAdapter extends BaseExpandableListAdapter {
LayoutInflater inflater = LayoutInflater.from(getApplicationContext());
public Object getChild(int groupPosition, int childPosition) {
try {
Iterator<ArrayList<ServiceInfo>> it = DETAILS.values().iterator();
int i = 0;
while (it.hasNext()) {
ArrayList<ServiceInfo> type = it.next();
if (i == groupPosition) {
ServiceInfo service = type.get(childPosition);
ServiceInfo resolvedService = jmdns.getServiceInfo(service.getType(), service.getName());
if (resolvedService != null) {
service = resolvedService;
}
StringBuffer buf = new StringBuffer();
buf.append("<b>");
buf.append(service.getName());
buf.append("</b><br/>");
buf.append(service.getTypeWithSubtype());
buf.append("<br/>");
buf.append(service.getServer());
buf.append(':');
buf.append(service.getPort());
buf.append("<br/>");
buf.append(service.getInetAddresses()[0]);
buf.append("<br/>");
for (Enumeration<String> names = service.getPropertyNames(); names.hasMoreElements();) {
buf.append("<br/>");
String prop = names.nextElement();
buf.append("<b>");
buf.append(prop);
buf.append("</b>");
buf.append(" = ");
buf.append("<i>");
buf.append(service.getPropertyString(prop));
buf.append("</i>");
}
return buf.toString();
}
i++;
}
} catch (Exception e) {
Log.w("Exception", e);
}
return "Not Available";
}
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
public int getChildrenCount(int groupPosition) {
Iterator<ArrayList<ServiceInfo>> it = DETAILS.values().iterator();
int i = 0;
while (it.hasNext()) {
ArrayList<ServiceInfo> type = it.next();
if (i == groupPosition) {
return type.size();
}
i++;
}
return 1;
}
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
convertView = this.inflater.inflate(R.layout.child_row, parent, false);
((TextView) convertView.findViewById(R.id.childvalue)).setText(Html.fromHtml(getChild(groupPosition, childPosition).toString()));
return convertView;
}
public Object getGroup(int groupPosition) {
return GROUPS.get(groupPosition);
}
public int getGroupCount() {
return GROUPS.size();
}
public long getGroupId(int groupPosition) {
return groupPosition;
}
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
convertView = this.inflater.inflate(R.layout.group_row, parent, false);
ServiceType type = (ServiceType) getGroup(groupPosition);
ImageView imageView = (ImageView) convertView.findViewById(R.id.serviceicon);
imageView.setImageResource(type.getImageIcon());
((TextView) convertView.findViewById(R.id.service)).setText(type.toString());
return convertView;
}
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
public boolean hasStableIds() {
return true;
}
}
}
Have a look at http://developer.android.com/training/connect-devices-wirelessly/nsd.html - that should get you started if you are running on Android
I have recently implement wifi direct into my project,my aim is pass string value between two wifidirect connected devices when some of my app condition satisfies.right now i have listed all peers and also made connection between the selected peer.what my idea is to pass a json file between the devices.so before try to execute that idea i try to pass a image file between two devices.i followed the steps from the android wifidirect tutorial.listing peers and the connection between the peers is success full but i cant pass the data between the devices.the follwing is my code.
FileTransferService.java
package jing.app.directwifi;
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 = "jing.app.directwifi.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("connected", "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("exp", e.toString());
}
MainActivity.copyFile(is, stream);
Log.d("exp" ,"Client: Data written");
} catch (IOException e) {
Log.e("exp", e.getMessage());
} finally {
if (socket != null) {
if (socket.isConnected()) {
try {
socket.close();
} catch (IOException e) {
// Give up
e.printStackTrace();
}
}
}
}
}
}
}
Main Activity.java
package jing.app.directwifi;
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;
import java.util.ArrayList;
import java.util.Collection;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.p2p.WifiP2pConfig;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pDeviceList;
import android.net.wifi.p2p.WifiP2pInfo;
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.ConnectionInfoListener;
import android.net.wifi.p2p.WifiP2pManager.PeerListListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener, android.content.DialogInterface.OnClickListener, ConnectionInfoListener {
private WifiP2pManager mManager;
private Channel mChannel;
private BroadcastReceiver mReceiver;
private IntentFilter mIntentFilter;
private Button mDiscover;
private TextView mDevices;
public ArrayAdapter mAdapter;
private ArrayList<WifiP2pDevice> mDeviceList = new ArrayList<WifiP2pDevice>();
protected static final int CHOOSE_FILE_RESULT_CODE = 20;
int flag=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDiscover = (Button) findViewById(R.id.discover);
mDiscover.setOnClickListener(this);
mDevices = (TextView) findViewById(R.id.peers);
mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
mChannel = mManager.initialize(this, getMainLooper(), null);
mReceiver = new WiFiDirectReceiver(mManager, mChannel, this);
mIntentFilter = new IntentFilter();
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
}
#Override
protected void onResume() {
super.onResume();
registerReceiver(mReceiver, mIntentFilter);
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(mReceiver);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
private class WiFiDirectReceiver extends BroadcastReceiver {
private WifiP2pManager mManager;
private Channel mChannel;
private MainActivity mActivity;
public WiFiDirectReceiver(WifiP2pManager manager, Channel channel, MainActivity activity) {
super();
mManager = manager;
mChannel = channel;
mActivity = activity;
}
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {
int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
String title = "ANDROID_ID[" + getAndroid_ID() + "]";
title += " MAC[" + getMACAddress() + "]";
Toast.makeText(mActivity, "Wi-Fi Direct is enabled."+title, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(mActivity, "Wi-Fi Direct is disabled.", Toast.LENGTH_SHORT).show();
}
} else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
if (mManager != null) {
mManager.requestPeers(mChannel, new PeerListListener() {
#Override
public void onPeersAvailable(WifiP2pDeviceList peers) {
if (peers != null) {
mDeviceList.addAll(peers.getDeviceList());
ArrayList<String> deviceNames = new ArrayList<String>();
for (WifiP2pDevice device : mDeviceList) {
deviceNames.add(device.deviceName);
}
if (deviceNames.size() > 0) {
mAdapter = new ArrayAdapter<String>(mActivity, android.R.layout.simple_list_item_1, deviceNames);
if(flag==0)
{
flag=1;
showDeviceListDialog();
}
} else {
Toast.makeText(mActivity, "Device list is empty.", Toast.LENGTH_SHORT).show();
}
}
}
});
}
} else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
} else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {
}
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.discover:
onDiscover();
break;
}
}
private void onDiscover() {
mManager.discoverPeers(mChannel, new ActionListener() {
#Override
public void onSuccess() {
Toast.makeText(MainActivity.this, "Discover peers successfully.", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(int reason) {
Toast.makeText(MainActivity.this, "Discover peers failed.", Toast.LENGTH_SHORT).show();
}
});
}
private void showDeviceListDialog() {
DeviceListDialog deviceListDialog = new DeviceListDialog();
deviceListDialog.show(getFragmentManager(), "devices");
}
private class DeviceListDialog extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Select a device")
.setSingleChoiceItems(mAdapter, 0, MainActivity.this)
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
return builder.create();
}
}
#Override
public void onClick(DialogInterface dialog, int which) {
onDeviceSelected(which);
dialog.dismiss();
}
private void onDeviceSelected(int which) {
WifiP2pDevice device = mDeviceList.get(which);
if (device == null) {
return;
}
WifiP2pConfig config = new WifiP2pConfig();
config.deviceAddress = device.deviceAddress;
mManager.connect(mChannel, config, new ActionListener() {
#Override
public void onSuccess() {
Toast.makeText(MainActivity.this, "Connected", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, CHOOSE_FILE_RESULT_CODE);
}
#Override
public void onFailure(int reason) {
Toast.makeText(MainActivity.this, "Failed to connect", Toast.LENGTH_SHORT).show();
}
});
}
/**
* ANDROID_ID
*/
private String getAndroid_ID() {
return Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
}
/**
* Wi-Fi MAC
*/
private String getMACAddress() {
WifiManager manager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = manager.getConnectionInfo();
String mac = wifiInfo.getMacAddress();
// After the group negotiation, we assign the group owner as the file
// server. The file server is single threaded, single connection server
// socket.
new FileServerAsyncTask(getApplicationContext())
.execute();
return mac;
}
#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();
Log.d("intent", "Intent----------- " + uri);
Intent serviceIntent = new Intent(MainActivity.this, FileTransferService.class);
serviceIntent.setAction(FileTransferService.ACTION_SEND_FILE);
serviceIntent.putExtra(FileTransferService.EXTRAS_FILE_PATH, uri.toString());
serviceIntent.putExtra(FileTransferService.EXTRAS_GROUP_OWNER_ADDRESS,
getMACAddress());
serviceIntent.putExtra(FileTransferService.EXTRAS_GROUP_OWNER_PORT, 8988);
startService(serviceIntent);
}
/**
* 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;
/**
* #param context
* #param statusText
*/
public FileServerAsyncTask(Context context) {
this.context = context;
}
#Override
protected String doInBackground(Void... params) {
try {
System.out.println("insideeeeeeeeeeeeeeeeeeeeeeee");
ServerSocket serverSocket = new ServerSocket(8988);
Log.d("Server: Socket opened", "Server: Socket opened");
Socket client = serverSocket.accept();
Log.d("Server: connection done", "Server: connection done");
final File f = new File(Environment.getExternalStorageDirectory() + "/"
+ context.getPackageName() + "/wifip2pshared-" + System.currentTimeMillis()
+ ".jpg");
File dirs = new File(f.getParent());
if (!dirs.exists())
dirs.mkdirs();
f.createNewFile();
Log.d("server: copying files ", "server: copying files " + f.toString());
InputStream inputstream = client.getInputStream();
copyFile(inputstream, new FileOutputStream(f));
serverSocket.close();
return f.getAbsolutePath();
} catch (IOException e) {
Log.e("exp", e.getMessage());
System.out.println(":iooo:"+e);
return null;
}
}
/*
* (non-Javadoc)
* #see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
#Override
protected void onPostExecute(String result) {
if (result != null) {
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" + result), "image/*");
context.startActivity(intent);
}
}
/*
* (non-Javadoc)
* #see android.os.AsyncTask#onPreExecute()
*/
#Override
protected void onPreExecute() {
}
}
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("exp", e.toString());
return false;
}
return true;
}
#Override
public void onConnectionInfoAvailable(WifiP2pInfo info) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "connectioninfoo", 3000).show();
}
}
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="jing.app.directwifi"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="16" />
<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:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="jing.app.directwifi.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>
<!-- Used for transferring files after a successful connection -->
<service
android:name=".FileTransferService"
android:enabled="true" />
</application>
</manifest>
These are files used in my code .form the tutorial i have found that
new FileServerAsyncTask(getApplicationContext())
.execute();
where the the incomming data is begin accepted so when i need to execute this asyn thread,so anyone help me in which portion i have made the mistake.how can i transfer the file between devices .
The android code from the demo wifi direct project is able to pass file is unidirectional. ie. you can send file from client to server only. You need furthur modifications to make it work in both direction.
EDIT 2:
For that you need to know the IP address of both connected peers. Use the following function which I made following various sources with my modifications wherever appropriate.
public static String getIpAddress() {
try {
List<NetworkInterface> interfaces = Collections
.list(NetworkInterface.getNetworkInterfaces());
/*
* for (NetworkInterface networkInterface : interfaces) { Log.v(TAG,
* "interface name " + networkInterface.getName() + "mac = " +
* getMACAddress(networkInterface.getName())); }
*/
for (NetworkInterface intf : interfaces) {
if (!getMACAddress(intf.getName()).equalsIgnoreCase(
Globals.thisDeviceAddress)) {
// Log.v(TAG, "ignore the interface " + intf.getName());
// continue;
}
if (!intf.getName().contains("p2p"))
continue;
Log.v(TAG,
intf.getName() + " " + getMACAddress(intf.getName()));
List<InetAddress> addrs = Collections.list(intf
.getInetAddresses());
for (InetAddress addr : addrs) {
// Log.v(TAG, "inside");
if (!addr.isLoopbackAddress()) {
// Log.v(TAG, "isnt loopback");
String sAddr = addr.getHostAddress().toUpperCase();
Log.v(TAG, "ip=" + sAddr);
boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);
if (isIPv4) {
if (sAddr.contains("192.168.49.")) {
Log.v(TAG, "ip = " + sAddr);
return sAddr;
}
}
}
}
}
} catch (Exception ex) {
Log.v(TAG, "error in parsing");
} // for now eat exceptions
Log.v(TAG, "returning empty ip address");
return "";
}
public static String getMACAddress(String interfaceName) {
try {
List<NetworkInterface> interfaces = Collections
.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface intf : interfaces) {
if (interfaceName != null) {
if (!intf.getName().equalsIgnoreCase(interfaceName))
continue;
}
byte[] mac = intf.getHardwareAddress();
if (mac == null)
return "";
StringBuilder buf = new StringBuilder();
for (int idx = 0; idx < mac.length; idx++)
buf.append(String.format("%02X:", mac[idx]));
if (buf.length() > 0)
buf.deleteCharAt(buf.length() - 1);
return buf.toString();
}
} catch (Exception ex) {
} // for now eat exceptions
return "";
/*
* try { // this is so Linux hack return
* loadFileAsString("/sys/class/net/" +interfaceName +
* "/address").toUpperCase().trim(); } catch (IOException ex) { return
* null; }
*/
}
I think the way you initialize client makes the problem.
You need to call this
new FileServerAsyncTask(getApplicationContext()).execute();
after the connection is established and check if it's a client.
Now you are creating a client socket only if it is a server(group owner) and always when you call to get a MAC address.
So on the client side you are not intializing the socket and so not able to receive the file.
Once check the WifiDirect sample demo provided in the SDK, you may get more idea.