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
Related
I am trying to create an app where the app will connect to a Wi-Fi.
It is connecting to Wifi in all Android devices below android 6. But in Android 6, it will connect and drop after sometime say 10-20 seconds. Below is the complete Wifi Manager code.
Am I doing anything wrong in the below code.
I am asking for runtime LOCATION permission and also will ask to switch on the location. All manifest permissions are added in Manifest.
ACCESS_WIFI_STATE, CHANGE_WIFI_STATE, CHANGE_NETWORK_STATE,ACCESS_NETWORK_STATE,
ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION.
public class WifiManager implements Handler.Callback {
private static final String TAG = WifiManager.class.getSimpleName();
private Handler handler;
private Context reactContext;
private static final String WIFI_EVENT_NAME = "WiFiStatusEvent";
private static final String WIFI_STATUS = "WiFiStatus";
private static final int STATE_UNKNOWN = 0;
private static final int STATE_WIFI_OFF = 1;
private static final int STATE_WIFI_ON = 2;
private static final int STATE_SSID_VISIBLE = 3;
private static final int STATE_SSID_CONFIGURED = 4;
private static final int STATE_SSID_ASSOCIATING = 5;
private static final int STATE_SSID_ASSOCIATED = 6;
// A slight delay after the wifi says it is connected before we return to the calling app.
// (Sometimes the wifi isn't quite ready yet, even though it says it is)
private static final long DELAY_AFTER_CONNECTION_TIMEOUT = 1000 * 2;
// ESSID connect default timeout
private static final long DEFAULT_TARGET_NETWORK_CONNECT_TIMEOUT = 15 * 1000;
// Internal connection progress states
private int state = STATE_UNKNOWN;
// The system wifi manager
private android.net.wifi.WifiManager wifi;
// The application context to use for system functions
private String targetSSID = null;
// The given callback to message when we are done
private Handler timeoutHandler = null;
private static long timeout = 500000;
public WifiManager(Context reactContext) {
this.reactContext = reactContext;
wifi = (android.net.wifi.WifiManager) reactContext.getApplicationContext().getSystemService(WIFI_SERVICE);
}
public void connectToHost(Context context, String host, String password) {
WifiConfiguration wc = new WifiConfiguration();
wc.SSID = host;
//wc.preSharedKey = password;
int netId = wifi.addNetwork(wc);
try {
wifi.enableNetwork(netId, true);
wifi.setWifiEnabled(true);
System.out.println("enabled network");
} catch (Exception e) {
e.printStackTrace();
System.out.println(e.getMessage());
}
}
public void connectToHost2(Context context, String host, String password) {
WifiConfiguration wc = new WifiConfiguration();
wc.SSID = host;
//wc.preSharedKey = password;
wc.status = WifiConfiguration.Status.ENABLED;
wc.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
wc.allowedProtocols.set(WifiConfiguration.Protocol.WPA); // For WPA
wc.allowedProtocols.set(WifiConfiguration.Protocol.RSN); // For WPA2
wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
int netId = wifi.addNetwork(wc);
WifiConfiguration wifiConfig = setWifiConfiguration(targetSSID, WifiConfiguration.KeyMgmt.NONE);
int networkId = wifi.addNetwork(wifiConfig);
logInfo(TAG, "networkId :: " + networkId);
wifi.saveConfiguration();
try {
wifi.enableNetwork(netId, true);
wifi.setWifiEnabled(true);
System.out.println("enabled network");
} catch (Exception e) {
e.printStackTrace();
System.out.println(e.getMessage());
}
}
public void connectToWifi() {
try {
WifiConfiguration wc = new WifiConfiguration();
WifiInfo wifiInfo = wifi.getConnectionInfo();
wc.SSID = "\"WIFI_SSID\"";
wc.priority = 1;
//wc.preSharedKey = "\"PASSWORD\"";
wc.status = WifiConfiguration.Status.ENABLED;
wc.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
int netId = wifi.addNetwork(wc);
if (netId == -1) {
netId = getExistingNetworkId(wc.SSID);
}
wifi.disconnect();
wifi.enableNetwork(netId, true);
wifi.reconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
private int getExistingNetworkId(String SSID) {
List<WifiConfiguration> configuredNetworks = wifi.getConfiguredNetworks();
if (configuredNetworks != null) {
for (WifiConfiguration existingConfig : configuredNetworks) {
if (existingConfig.SSID.equals(SSID)) {
return existingConfig.networkId;
}
}
}
return -1;
}
public void connectToWifi(String wifiSSID) {
logInfo(TAG, "Connecting to " + wifiSSID);
if (null == handler) {
handler = new Handler(this);
}
if (null == wifiSSID || wifiSSID.isEmpty()) {
return;
}
displayLocationSettingsRequest(reactContext);
this.targetSSID = wifiSSID;
//removeNetwork();
connectToTargetNetwork();
}
//#ReactMethod
public void isConnected(String wifiSSID) {
this.targetSSID = wifiSSID;
}
#Override
public boolean handleMessage(Message msg) {
if (null == msg) {
logError(TAG, "Callback, error");
return false;
}
if (null == msg.obj) {
logError(TAG, "Callback, error");
return false;
}
WifiStatus wifiStatus = (WifiStatus) msg.obj;
if (null != wifiStatus) {
logInfo(TAG, "ID :: " + wifiStatus.getId());
}
return false;
}
/**
* WIFI state callback - Listening for WIFI on/off transitions
*/
private BroadcastReceiver wifiStateReceiver = new BroadcastReceiver() {
public void onReceive(Context c, Intent intent) {
logInfo(TAG, "WifiStateReceiver - onReceive" + intent.getPackage());
ConnectivityManager cm = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo currentNetworkInfo = cm.getActiveNetworkInfo();
if (currentNetworkInfo != null && "WIFI".equals(currentNetworkInfo.getTypeName())) {
logInfo(TAG, "NetworkInfo - TypeName = " + currentNetworkInfo.getTypeName() + ", state = " + currentNetworkInfo.getState());
if (currentNetworkInfo.getState() == NetworkInfo.State.CONNECTED) {
if (isConnectedToTargetNetwork()) {
sendCallbackMessage(handler, WifiStatus.ASSOCIATED);
delayBeforeFinish();
return;
}
}
// We are connected
if (!isConnectedToTargetNetwork()) {
state = STATE_WIFI_ON;
logInfo(TAG, "Starting wifi scan...");
wifi.startScan();
}
}
}
};
/**
* WIFI state callback - Listening for network scan completion
*/
private BroadcastReceiver wifiScanResultsReceiver = new BroadcastReceiver() {
public void onReceive(Context c, Intent intent) {
Logger.logWarning(TAG, "WifiScanResultsReceiver - onReceive");
// Don't care unless wifi is on
if (state != STATE_WIFI_ON) {
return;
}
// Check if we are already connected to target network
if (isConnectedToTargetNetwork()) {
sendCallbackMessage(handler, WifiStatus.ASSOCIATED);
delayBeforeFinish();
return;
}
// Check if the target network showed up in the scan
if (isOurNetworkVisible()) {
logInfo(TAG, "Scan found our ESSID:" + targetSSID);
connectToVisibleNetwork();
} else {
logInfo(TAG, "Scan DID NOT FIND ESSID:" + targetSSID);
}
}
};
/**
* method to return the current WIFI connectivity state
*
* #param targetSSID the network SSID we are hoping to be associated with
* #return connection status
*/
public WifiStatus getStatus(String targetSSID) {
// Get a temporary WiFiManager instance since this is a static method
// Check if wifi is on
if (!wifi.isWifiEnabled()) {
return WifiStatus.WIFI_OFF;
}
// Check if associated to anything
WifiInfo wifiInfo = wifi.getConnectionInfo();
if (wifiInfo == null || wifiInfo.getSSID() == null) {
return WifiStatus.WIFI_ON;
}
// Check if associated to given SSID
if (wifiInfo.getSSID().equals(targetSSID)) {
return WifiStatus.ASSOCIATED;
}
// Check if given SSID is visible
List<ScanResult> wifiList = wifi.getScanResults();
for (ScanResult info : wifiList) {
if (targetSSID.equals(info.SSID)) {
return WifiStatus.SSID_VISIBLE;
}
}
return WifiStatus.SSID_NOT_VISIBLE;
}
/**
* Method to turn off WiFi
*
* #param context the callers application context
* #return true if successful
*/
public boolean turnOffWifi(Context context) {
// Get a temporary WiFiManager instance since this is a static method
return wifi.setWifiEnabled(false);
}
/**
* Sends a message to the callback.
*
* #param callback the callback to send to
*/
private static void sendCallbackMessage(Handler callback, WifiStatus status) {
if (null != callback) {
Message message = callback.obtainMessage();
if (null != message) {
message.obj = status;
callback.sendMessage(message);
}
}
}
/**
* Connects to the given ESSID. Turns on WiFi if necessary.
* Once the operation is complete (whether successful or not),
* it sends a message to the given Handler with the state of the WiFi connection.
*/
public void connectToTargetNetwork() {
// Add timeout override to get out no matter what happens...
timeoutHandler = new Handler();
timeoutHandler.postDelayed(masterCompletionTimeout, timeout);
state = STATE_UNKNOWN;
// Check if we are already connected to target network
if (isConnectedToTargetNetwork()) {
sendCallbackMessage(handler, WifiStatus.ASSOCIATED);
return;
}
registerReceivers();
// Check if WIFI is turned on
// Not enabled, turn it on!
if (!wifi.isWifiEnabled()) {
logInfo(TAG, "Enabling WIFI...");
state = STATE_WIFI_OFF;
boolean success = wifi.setWifiEnabled(true);
if (!success) {
sendCallbackMessage(handler, WifiStatus.WIFI_OFF);
}
// Wait for connection callback
return;
}
// We are connected, check if target SSID is visible
state = STATE_WIFI_ON;
logInfo(TAG, "Starting wifi scan...");
wifi.startScan();
}
public void registerReceivers() {
// Register system WIFI state callbacks
reactContext.getApplicationContext().registerReceiver(wifiStateReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
reactContext.getApplicationContext().registerReceiver(wifiScanResultsReceiver, new IntentFilter(android.net.wifi.WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
}
/**
* Perform internal cleanup before returning response to caller
*/
public void cleanupConnectToTargetNetwork() {
logInfo(TAG, "cleanupConnectToTargetNetwork");
// Unregister all internal WiFi state receivers
if (reactContext.getApplicationContext() != null) {
// Unregister all our WIFI status receivers
try {
if (null != wifiStateReceiver) {
reactContext.getApplicationContext().unregisterReceiver(wifiStateReceiver);
}
} catch (Exception e) {
logError(TAG, e.getMessage());
}
try {
if (null != wifiScanResultsReceiver) {
reactContext.getApplicationContext().unregisterReceiver(wifiScanResultsReceiver);
}
} catch (Exception e) {
logError(TAG, e.getMessage());
}
}
// Cancel our master timeout
if (timeoutHandler != null) {
try {
timeoutHandler.removeCallbacks(masterCompletionTimeout);
} catch (Exception e) {
logError(TAG, e.getMessage());
}
timeoutHandler = null;
}
try {
state = STATE_UNKNOWN;
// Get the final WiFi status and send it back to the caller
WifiStatus status = getStatus(targetSSID);
logInfo(TAG, "cleanupConnectToTargetNetwork - WiFi status=" + status.getName());
sendCallbackMessage(handler, status);
} catch (Exception e) {
logError(TAG, "Error IN Wifi :: " + e);
}
}
/**
* Provides a slight delay before sending a results message to the caller.
* This method is used when the requested network connection has been made successfully.
* We have seen that when the OS reports the WiFi is ready, it might actually not be for a couple more seconds.
* So we impart a slight delay to cover this.
*/
private void delayBeforeFinish() {
if (timeoutHandler != null) {
timeoutHandler.removeCallbacks(masterCompletionTimeout);
}
if (timeoutHandler == null) {
timeoutHandler = new Handler();
}
timeoutHandler.postDelayed(masterCompletionTimeout, DELAY_AFTER_CONNECTION_TIMEOUT);
}
/**
* Connect to our target SSID.
* A prerequisite to calling this function is that the SSID is visible from a network scan.
*/
private void connectToVisibleNetwork() {
logInfo(TAG, "connectToVisibleNetwork");
// SSID is visible, check if it is configured
state = STATE_SSID_VISIBLE;
if (state == STATE_SSID_ASSOCIATING) {
logError(TAG, "Associating now...");
return;
}
// Check if the target SSID is configured on this device
int networkId = isNetworkConfigured(targetSSID);
logInfo(TAG, "Our network is configured returned:" + networkId);
if (networkId < 0) {
// Network not configured, Add the network
logInfo(TAG, "Adding our network to configuration...");
WifiConfiguration wifiConfig = setWifiConfiguration(targetSSID, WifiConfiguration.KeyMgmt.NONE);
networkId = wifi.addNetwork(wifiConfig);
logInfo(TAG, "addNetwork returned: " + networkId);
if (networkId < 0) {
return;
}
// Network added, save the changes
wifi.saveConfiguration();
}
setWifiConfiguration(targetSSID, WifiConfiguration.KeyMgmt.NONE);
wifi.disconnect();
//wifi.saveConfiguration();
// Network is configured on this device
state = STATE_SSID_CONFIGURED;
// Connect to network
state = STATE_SSID_ASSOCIATING;
boolean success = wifi.enableNetwork(networkId, true);
//c2();
wifi.reconnect();
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
// ConnectivityManager.setProcessDefaultNetwork(networkId);
// }
//ConnectivityManager.
logInfo(TAG, "Enable our SSID returned:" + success);
if (success) {
logInfo(TAG, "connectToVisibleNetwork, Success...");
}
//connectToHost2(getReactApplicationContext(), targetSSID, "");
return;
}
#NonNull
private WifiConfiguration setWifiConfiguration(String targetSSID, int none) {
WifiConfiguration wc = new WifiConfiguration();
wc.SSID = formatSSIDWithQuotes(targetSSID);
wc.hiddenSSID = false;
/* wifiConfig.priority = 1;
wifiConfig.allowedKeyManagement.set(none);
wifiConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
wifiConfig.allowedKeyManagement.set(none);
wifiConfig.status = WifiConfiguration.Status.ENABLED;*/
wc.status = WifiConfiguration.Status.ENABLED;
wc.priority = 1;
wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
wc.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
wc.allowedAuthAlgorithms.set(0);
wc.status = 2;
wc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
wc.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
wc.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
wc.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
assignHighestPriority(wc);
//wifi.updateNetwork(wc);
return wc;
}
/**
* Check if our target SSID is visible to the WIFI radio
*
* #return true if visible
*/
public boolean isOurNetworkVisible() {
// Get a list of visible SSID's and iterate through them
List<ScanResult> wifiList = wifi.getScanResults();
for (ScanResult info : wifiList) {
Logger.logWarning(TAG, "Scan found ESSID:" + info.SSID + ", Strength :: " + info.level);
// Check if each one is ours
if (null != targetSSID && targetSSID.equals(info.SSID)) {
return true;
}
}
return false;
}
/* Check the strength of the WiFi
0-3, 3=good
*/
public boolean isInRange() {
// Get a list of visible SSID's and iterate through them
List<ScanResult> wifiList = wifi.getScanResults();
for (ScanResult info : wifiList) {
if (null != targetSSID && targetSSID.equals(info.SSID)) {
int rssi = wifi.getConnectionInfo().getRssi();
int level = wifi.calculateSignalLevel(rssi, 3);
Logger.logWarning(TAG, "Scan found ESSID:" + info.SSID + ", Strength :: " + info.level + " , Calculated Level :: " + level);
return level > 0;
}
}
return false;
}
/**
* Check if we are connected to the target SSID
*
* #return
*/
private boolean isConnectedToTargetNetwork() {
try {
wifi = (android.net.wifi.WifiManager) reactContext.getApplicationContext().getSystemService(WIFI_SERVICE);
if (null == wifi) {
return false;
}
if (!wifi.isWifiEnabled()) {
return false;
}
WifiInfo wifiInfo = wifi.getConnectionInfo();
if (null != targetSSID) {
targetSSID = targetSSID.replaceAll("\"", "");
}
String ssid = wifiInfo.getSSID();
if (null != ssid) {
ssid = ssid.replaceAll("\"", "");
}
return wifiInfo != null && wifiInfo.getSSID() != null && ssid.equals(targetSSID);
} catch (Exception e) {
logError(TAG, "<< isConnectedToTargetNetwork >> " + e);
return false;
}
}
/**
* Check if the given network is configured on this device
*
* #param ssid the SSID to check
* #return the networkId of this SSID or -1 if not found
*/
private int isNetworkConfigured(String ssid) {
logInfo(TAG, "isNetworkConfigured for >" + ssid + "<");
// The SSID's returned by the system have quotes around them
String formattedSSID = formatSSIDWithQuotes(ssid);
try {
// Get the configured networks (SSID's) and iterate though them
List<WifiConfiguration> networksList = wifi.getConfiguredNetworks();
for (WifiConfiguration config : networksList) {
logInfo(TAG, "Config - essid =: " + config.SSID + ", id =" + config.networkId);
// Is this our SSID?
if (formattedSSID.equals(config.SSID)) {
logInfo(TAG, "Network IS configured - essid=:" + config.SSID + ", id=" + config.networkId);
wifi.saveConfiguration();
// Return the internal network id of this SSID
return config.networkId;
}
}
} catch (Exception e) {
logInfo(TAG, "isNetworkConfigured exception - " + e.getMessage());
}
// The given SSID was not found
return -1;
}
private String formatSSIDWithQuotes(String ssid) {
return "\"" + ssid + "\"";
}
public static void displayLocationSettingsRequest(final Context activity) {
final Message message = new Message();
GoogleApiClient googleApiClient = new GoogleApiClient.Builder(activity)
.addApi(LocationServices.API).build();
googleApiClient.connect();
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(30 * 1000);
locationRequest.setFastestInterval(5 * 1000);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
builder.setAlwaysShow(true);
PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
#Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
final LocationSettingsStates state = result.getLocationSettingsStates();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
// All location settings are satisfied. The client can initialize location
// requests here.
message.arg1 = 1;
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
message.arg1 = 0;
// Location settings are not satisfied. But could be fixed by showing the user
// a dialog.
// try {
// // Show the dialog by calling startResolutionForResult(),
// // and check the result in onActivityResult().
// //status.startResolutionForResult(activity, 1000);
// } catch (IntentSender.SendIntentException ignored) {}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
// Location settings are not satisfied. However, we have no way to fix the
// settings so we won't show the dialog.
message.arg1 = 0;
break;
}
}
});
}
//To tell OS to give preference to this network
private void assignHighestPriority(WifiConfiguration config) {
List<WifiConfiguration> configuredNetworks = wifi.getConfiguredNetworks();
if (configuredNetworks != null) {
for (WifiConfiguration existingConfig : configuredNetworks) {
if (config.priority <= existingConfig.priority) {
config.priority = existingConfig.priority + 1;
}
}
}
}
/////
}
I find decision. You must add a traffic flow every 1 seconds for different site.
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'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