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
Related
I am making my first Socket.io based android application. The socket sends and receives data from a web service. There are a number of screens in the application for different features. How do i use the same socket connection in these different activities.
I have tried setting and storing the Socket Object in the Application class and it appears to work well but when the application goes into the background and left there for some time the application is killed and the socket object is then NULL causing the aoo to crash with a null pointer exception.
public class MyApplication extends Application {
private Socket mSocket;
private final String TAG = "Application Class";
public Socket getSocket() {
return mSocket;
}
public Socket createSocket() {
try {
Manager manager = new Manager(new URI("http://0.0.0.0"));
} catch (URISyntaxException URIse) {
URIse.printStackTrace();
}
return mSocket;
}
}
Access the socket in the activities
MyApplication app;
app = (MyApplication ) getApplication();
app.getSocket;
You can create a singleton manager class for socket. It will allow you to keep single socket connection accessible to entire app. See following code and change it according to your requirement
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.Looper;
import android.os.PowerManager;
import android.util.Log;
import com.myapp.app.ui.adapter.OnSocketConnectionListener;
import java.util.ArrayList;
import java.util.List;
import io.socket.client.IO;
import io.socket.client.Socket;
import io.socket.emitter.Emitter;
/**
* Created by penguin on 6/30/2016.
* <p/>
* SocketManager manages socket and internet connection.
* It also provide listeners for connection status
*/
public class SocketManager {
/**
* The constant STATE_CONNECTING.
*/
public static final int STATE_CONNECTING = 1;
/**
* The constant STATE_CONNECTED.
*/
public static final int STATE_CONNECTED = 2;
/**
* The constant STATE_DISCONNECTED.
*/
public static final int STATE_DISCONNECTED = 3;
/**
* The constant CONNECTING.
*/
public static final String CONNECTING = "Connecting";
/**
* The constant CONNECTED.
*/
public static final String CONNECTED = "Connected";
/**
* The constant DISCONNECTED.
*/
public static final String DISCONNECTED = "Disconnected";
private static SocketManager instance;
private SocketManager() {
}
/**
* Gets instance.
*
* #return the instance
*/
public synchronized static SocketManager getInstance() {
if (instance == null) {
instance = new SocketManager();
}
return instance;
}
/**
* The constant TAG.
*/
public static final String TAG = SocketManager.class.getSimpleName();
private Socket socket;
private List<OnSocketConnectionListener> onSocketConnectionListenerList;
/**
* Connect socket.
*
* #param token the token
* #param userId the user id
* #param host the host
* #param port the port
*/
public void connectSocket(String token,String userId, String host, String port) {
try {
if(socket==null){
String serverAddress = host+":"+port;
IO.Options opts = new IO.Options();
opts.forceNew = true;
opts.reconnection = true;
opts.reconnectionAttempts=5;
opts.secure = true;
opts.query = "token=" + token + "&" + "user_id=" + userId;
socket = IO.socket(serverAddress, opts);
socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
#Override
public void call(Object... args) {
fireSocketStatus(SocketManager.STATE_CONNECTED);
Log.i(TAG, "socket connected");
}
}).on(Socket.EVENT_RECONNECTING, new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.e(TAG, "Socket reconnecting");
fireSocketStatus(SocketManager.STATE_CONNECTING);
}
}).on(Socket.EVENT_RECONNECT_FAILED, new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.e(TAG, "Socket reconnection failed");
// fireSocketStatusIntent(SocketManager.STATE_DISCONNECTED);
}
}).on(Socket.EVENT_RECONNECT_ERROR, new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.e(TAG, "Socket reconnection error");
// fireSocketStatus(SocketManager.STATE_DISCONNECTED);
}
}).on(Socket.EVENT_CONNECT_ERROR, new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.e(TAG, "Socket connect error");
fireSocketStatus(SocketManager.STATE_DISCONNECTED);
socket.disconnect();
}
}).on(Socket.EVENT_DISCONNECT, new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.e(TAG, "Socket disconnect event");
fireSocketStatus(SocketManager.STATE_DISCONNECTED);
}
}).on(Socket.EVENT_ERROR, new Emitter.Listener() {
#Override
public void call(Object... args) {
try {
final String error = (String) args[0];
Log.e(TAG + " error EVENT_ERROR ", error);
if (error.contains("Unauthorized") && !socket.connected()) {
if (onSocketConnectionListenerList != null) {
for (final OnSocketConnectionListener listener : onSocketConnectionListenerList) {
new Handler(Looper.getMainLooper())
.post(new Runnable() {
#Override
public void run() {
listener.onSocketEventFailed();
}
});
}
}
}
} catch (Exception e) {
Log.e(TAG, e.getMessage() != null ? e.getMessage() : "");
}
}
}).on("Error", new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.d(TAG, " Error");
}
});
socket.connect();
}else if(!socket.connected()){
socket.connect();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private int lastState = -1;
/**
* Fire socket status intent.
*
* #param socketState the socket state
*/
public synchronized void fireSocketStatus(final int socketState) {
if(onSocketConnectionListenerList !=null && lastState!=socketState){
lastState = socketState;
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
for(OnSocketConnectionListener listener: onSocketConnectionListenerList){
listener.onSocketConnectionStateChange(socketState);
}
}
});
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
#Override
public void run() {
lastState=-1;
}
},1000);
}
}
/**
* Fire internet status intent.
*
* #param socketState the socket state
*/
public synchronized void fireInternetStatusIntent(final int socketState) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
if(onSocketConnectionListenerList !=null){
for(OnSocketConnectionListener listener: onSocketConnectionListenerList){
listener.onInternetConnectionStateChange(socketState);
}
}
}
});
}
/**
* Gets socket.
*
* #return the socket
*/
public Socket getSocket() {
return socket;
}
/**
* Sets socket.
*
* #param socket the socket
*/
public void setSocket(Socket socket) {
this.socket = socket;
}
/**
* Destroy.
*/
public void destroy(){
if (socket != null) {
socket.off();
socket.disconnect();
socket.close();
socket=null;
}
}
/**
* Sets socket connection listener.
*
* #param onSocketConnectionListenerListener the on socket connection listener listener
*/
public void setSocketConnectionListener(OnSocketConnectionListener onSocketConnectionListenerListener) {
if(onSocketConnectionListenerList ==null){
onSocketConnectionListenerList = new ArrayList<>();
onSocketConnectionListenerList.add(onSocketConnectionListenerListener);
}else if(!onSocketConnectionListenerList.contains(onSocketConnectionListenerListener)){
onSocketConnectionListenerList.add(onSocketConnectionListenerListener);
}
}
/**
* Remove socket connection listener.
*
* #param onSocketConnectionListenerListener the on socket connection listener listener
*/
public void removeSocketConnectionListener(OnSocketConnectionListener onSocketConnectionListenerListener) {
if(onSocketConnectionListenerList !=null
&& onSocketConnectionListenerList.contains(onSocketConnectionListenerListener)){
onSocketConnectionListenerList.remove(onSocketConnectionListenerListener);
}
}
/**
* Remove all socket connection listener.
*/
public void removeAllSocketConnectionListener() {
if(onSocketConnectionListenerList !=null){
onSocketConnectionListenerList.clear();
}
}
/**
* The type Net receiver.
*/
public static class NetReceiver extends BroadcastReceiver {
/**
* The Tag.
*/
public final String TAG = NetReceiver.class.getSimpleName();
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager cm =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
SocketManager.getInstance().fireInternetStatusIntent(
isConnected?SocketManager.STATE_CONNECTED:SocketManager.STATE_DISCONNECTED);
if (isConnected) {
if(SocketManager.getInstance().getSocket()!=null
&& !SocketManager.getInstance().getSocket().connected()){
SocketManager.getInstance().fireSocketStatus(SocketManager.STATE_CONNECTING);
}
PowerManager powerManager =
(PowerManager) context.getSystemService(Context.POWER_SERVICE);
boolean isScreenOn;
if (android.os.Build.VERSION.SDK_INT
>= android.os.Build.VERSION_CODES.KITKAT_WATCH) {
isScreenOn = powerManager.isInteractive();
}else{
//noinspection deprecation
isScreenOn = powerManager.isScreenOn();
}
if (isScreenOn && SocketManager.getInstance().getSocket() !=null) {
Log.d(TAG, "NetReceiver: Connecting Socket");
if(!SocketManager.getInstance().getSocket().connected()){
SocketManager.getInstance().getSocket().connect();
}
}
}else{
SocketManager.getInstance().fireSocketStatus(SocketManager.STATE_DISCONNECTED);
if(SocketManager.getInstance().getSocket() !=null){
Log.d(TAG, "NetReceiver: disconnecting socket");
SocketManager.getInstance().getSocket().disconnect();
}
}
}
}
}
Connecting socket
You can connecting/disconnect socket from any activity or background service
SocketManager.getInstance().connectSocket(user.getToken(), user.getUserId(),
getResources().getString(R.string.host), "8000");
Update
If in background your app is killed socket will also destroy. If you want socket to remain connected in background you have to make you own logic with background service which has nothing to do with socket.
implement OnSocketConnectionListener
public interface OnSocketConnectionListener {
void onSocketEventFailed();
void onSocketConnectionStateChange(int socketState);
void onInternetConnectionStateChange(int socketState);
}
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 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.
I have created an app for tethering wifi on android devices
and here`s my code
WiFiAo.java
package com.gado.wifihotspot;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.util.Log;
import java.lang.reflect.Method;
import com.gado.wifihotspot.MainActivity;;
public class WifiAP extends Activity {
private static int constant = 0;
private static final int WIFI_AP_STATE_UNKNOWN = -1;
private static int WIFI_AP_STATE_DISABLING = 0;
private static int WIFI_AP_STATE_DISABLED = 1;
public int WIFI_AP_STATE_ENABLING = 2;
public int WIFI_AP_STATE_ENABLED = 3;
private static int WIFI_AP_STATE_FAILED = 4;
private final String[] WIFI_STATE_TEXTSTATE = new String[] {
"DISABLING","DISABLED","ENABLING","ENABLED","FAILED"
};
private WifiManager wifi;
private String TAG = "WifiAP";
private int stateWifiWasIn = -1;
private boolean alwaysEnableWifi = true; //set to false if you want to try and set wifi state back to what it was before wifi ap enabling, true will result in the wifi always being enabled after wifi ap is disabled
/**
* Toggle the WiFi AP state
* #param wifihandler
* #author http://stackoverflow.com/a/7049074/1233435
*/
public void toggleWiFiAP(WifiManager wifihandler, Context context) {
if (wifi==null){
wifi = wifihandler;
}
boolean wifiApIsOn = getWifiAPState()==WIFI_AP_STATE_ENABLED || getWifiAPState()==WIFI_AP_STATE_ENABLING;
new SetWifiAPTask(!wifiApIsOn,false,context).execute();
}
/**
* Enable/disable wifi
* #param true or false
* #return WifiAP state
* #author http://stackoverflow.com/a/7049074/1233435
*/
private int setWifiApEnabled(boolean enabled) {
Log.d(TAG, "*** setWifiApEnabled CALLED **** " + enabled);
WifiConfiguration config = new WifiConfiguration();
config.SSID = "My AP";
config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
//remember wirelesses current state
if (enabled && stateWifiWasIn==-1){
stateWifiWasIn=wifi.getWifiState();
}
//disable 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) {
}
}
Log.d(TAG, "disable wifi: done, pass: " + (10-loopMax));
}
//enable/disable wifi ap
int state = WIFI_AP_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, null, enabled); // true
method1.invoke(wifi, config, enabled); // true
Method method2 = wifi.getClass().getMethod("getWifiApState");
state = (Integer) method2.invoke(wifi);
} catch (Exception e) {
Log.e(WIFI_SERVICE, e.getMessage());
// toastText += "ERROR " + e.getMessage();
}
//hold thread up while processing occurs
if (!enabled) {
int loopMax = 10;
while (loopMax>0 && (getWifiAPState()==WIFI_AP_STATE_DISABLING || getWifiAPState()==WIFI_AP_STATE_ENABLED || getWifiAPState()==WIFI_AP_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 wifi if it was enabled beforehand
//this is somewhat unreliable and app gets confused and doesn't turn it back on sometimes so added toggle to always enable if you desire
if(stateWifiWasIn==WifiManager.WIFI_STATE_ENABLED || stateWifiWasIn==WifiManager.WIFI_STATE_ENABLING || stateWifiWasIn==WifiManager.WIFI_STATE_UNKNOWN || alwaysEnableWifi){
Log.d(TAG, "enable wifi: calling");
wifi.setWifiEnabled(true);
//don't hold things up and wait for it to get enabled
}
stateWifiWasIn = -1;
} else if (enabled) {
int loopMax = 10;
while (loopMax>0 && (getWifiAPState()==WIFI_AP_STATE_ENABLING || getWifiAPState()==WIFI_AP_STATE_DISABLED || getWifiAPState()==WIFI_AP_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
* #return WifiAP state
* #author http://stackoverflow.com/a/7049074/1233435
*/
public int getWifiAPState() {
int state = WIFI_AP_STATE_UNKNOWN;
try {
Method method2 = wifi.getClass().getMethod("getWifiApState");
state = (Integer) method2.invoke(wifi);
} catch (Exception e) {
}
if(state>=10){
//using Android 4.0+ (or maybe 3+, haven't had a 3 device to test it on) so use states that are +10
constant=10;
}
//reset these in case was newer device
WIFI_AP_STATE_DISABLING = 0+constant;
WIFI_AP_STATE_DISABLED = 1+constant;
WIFI_AP_STATE_ENABLING = 2+constant;
WIFI_AP_STATE_ENABLED = 3+constant;
WIFI_AP_STATE_FAILED = 4+constant;
Log.d(TAG, "getWifiAPState.state " + (state==-1?"UNKNOWN":WIFI_STATE_TEXTSTATE[state-constant]));
return state;
}
/**
* the AsyncTask to enable/disable the wifi ap
* #author http://stackoverflow.com/a/7049074/1233435
*/
class SetWifiAPTask extends AsyncTask<Void, Void, Void> {
boolean mMode; //enable or disable wifi AP
boolean mFinish; //finalize or not (e.g. on exit)
ProgressDialog d;
/**
* enable/disable the wifi ap
* #param mode enable or disable wifi AP
* #param finish finalize or not (e.g. on exit)
* #param context the context of the calling activity
* #author http://stackoverflow.com/a/7049074/1233435
*/
public SetWifiAPTask(boolean mode, boolean finish, Context context) {
mMode = mode;
mFinish = finish;
d = new ProgressDialog(context);
}
/**
* do before background task runs
* #author http://stackoverflow.com/a/7049074/1233435
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
d.setTitle("Turning WiFi Tethering " + (mMode?"on":"off") + "...");
d.setMessage("...please wait a moment.");
d.show();
}
/**
* do after background task runs
* #param aVoid
* #author http://stackoverflow.com/a/7049074/1233435
*/
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
try {
d.dismiss();
MainActivity.updateStatusDisplay();
} catch (IllegalArgumentException e) {
};
if (mFinish){
finish();
}
}
/**
* the background task to run
* #param params
* #author http://stackoverflow.com/a/7049074/1233435
*/
#Override
protected Void doInBackground(Void... params) {
setWifiApEnabled(mMode);
return null;
}
}
}
MainActivity.java
package com.gado.wifihotspot;
import android.app.Activity;
import android.content.Context;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.ImageButton;
public class MainActivity extends Activity {
boolean wasAPEnabled = false;
static WifiAP wifiAp;
private WifiManager wifi;
static ImageButton btnWifiToggle;
static CheckBox checkencrypted;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnWifiToggle = (ImageButton) findViewById(R.id.btnWifiToggle);
checkencrypted = (CheckBox) findViewById(R.id.checkBox1);
wifiAp = new WifiAP();
wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
btnWifiToggle.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
wifiAp.toggleWiFiAP(wifi, MainActivity.this);
}
});
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD|WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON|WindowManager.LayoutParams.FLAG_DIM_BEHIND);
}
#Override
public void onResume() {
super.onResume();
if (wasAPEnabled) {
if (wifiAp.getWifiAPState()!=wifiAp.WIFI_AP_STATE_ENABLED && wifiAp.getWifiAPState()!=wifiAp.WIFI_AP_STATE_ENABLING){
wifiAp.toggleWiFiAP(wifi, MainActivity.this);
}
}
updateStatusDisplay();
}
#Override
public void onPause() {
super.onPause();
boolean wifiApIsOn = wifiAp.getWifiAPState()==wifiAp.WIFI_AP_STATE_ENABLED || wifiAp.getWifiAPState()==wifiAp.WIFI_AP_STATE_ENABLING;
if (wifiApIsOn) {
wasAPEnabled = true;
wifiAp.toggleWiFiAP(wifi, MainActivity.this);
} else {
wasAPEnabled = false;
}
updateStatusDisplay();
}
public static void updateStatusDisplay() {
if (wifiAp.getWifiAPState()==wifiAp.WIFI_AP_STATE_ENABLED || wifiAp.getWifiAPState()==wifiAp.WIFI_AP_STATE_ENABLING) {
btnWifiToggle.setImageResource(R.drawable.off);
//findViewById(R.id.bg).setBackgroundResource(R.drawable.bg_wifi_on);
} else {
btnWifiToggle.setImageResource(R.drawable.on);
//findViewById(R.id.bg).setBackgroundResource(R.drawable.bg_wifi_off);
}
}
}
Now I want to add encryption for this tethering & WiFi hotspot name but I haven`t any idea about how to do that?
Update the setWifiApEnabled method in this way.This method provides open, WPA and WPA2 access to your app.
private int setWifiApEnabled(boolean enabled) {
Log.d(TAG, "*** setWifiApEnabled CALLED **** " + enabled);
WifiConfiguration config = new WifiConfiguration();
config.SSID = "My AP";
//changes added here
config.preSharedKey="yourpassword";//enter the set password here
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
.....
You can also try WPA_EAP for different KeyMgmt;
reference:
Unable to connect with WPA2 android
Leave it to the OS, and use WifiConfiguration.Protocol - there you can set it to WPA :)
More info here.
http://developer.android.com/reference/android/net/wifi/WifiConfiguration.html
gl hf
Refael
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.