3

I want to connect a hardware device to an android hotspot. My app will setup a hotspot and detect the device connecting.

I've tried using the p2p sample provided with SDK 21 but when the hotspot is enabled the WIFI_P2P_STATE_ENABLED tells me that P2P is disabled: http://developer.android.com/guide/topics/connectivity/wifip2p.html

Hence I'm assuming P2P does not equat to android hotspot management, please correct me if I'm wrong.

Can anyone reccomend which library to use to setup and detect connections on a wifi hotspot? Thanks, Ro

RonanE
  • 51
  • 1
  • 7
  • fi you want to connect to any wifi hotspot this would be apis-->http://stackoverflow.com/questions/26645943/how-to-change-wifi-advanced-option-from-code-that-chrome-lost-access-to-internet, can u specifically mention what would be the configuration which u would like to connect – KOTIOS Jan 14 '15 at 11:57
  • Thanks for the reply, I'm trying to create an AP that a device can connect to. Reading your example do you reckon creating a configuration for a wifi network using WifiManager.AddNetwork? – RonanE Jan 14 '15 at 12:13
  • I've just finished testing and WifiManager seems to be dedicated to managing what networks the phone can connect to, not the wifi AP, which is what I'm looking to control. Any pointers appreciated, thanks – RonanE Jan 14 '15 at 12:36
  • ok, what i can undestand is the list of wifi in android that you wanna control? – KOTIOS Jan 14 '15 at 12:50
  • No diva, I want to detect devices connecting to the phone's android AP. Thanks – RonanE Jan 14 '15 at 12:51
  • ok , will look into this and get back... – KOTIOS Jan 14 '15 at 13:03

2 Answers2

0

I found a solution for opening the AP programatically:

Android turn On/Off WiFi HotSpot programmatically

It appears you need to use reflection to access the ap functions in WifiManager

Community
  • 1
  • 1
RonanE
  • 51
  • 1
  • 7
0

For creating the hotspot use this function

/**
     * Start AccessPoint mode with the specified
     * configuration. If the radio is already running in
     * AP mode, update the new configuration
     * Note that starting in access point mode disables station
     * mode operation
     * @param wifiConfig SSID, security and channel details as part of WifiConfiguration
     * @return {@code true} if the operation succeeds, {@code false} otherwise
     */
    public boolean setWifiApEnabled(WifiConfiguration wifiConfig, boolean enabled) {
        try {
            if (enabled) { // disable WiFi in any case
                mWifiManager.setWifiEnabled(false);
            }

            Method method = mWifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
            return (Boolean) method.invoke(mWifiManager, wifiConfig, enabled);
        } catch (Exception e) {
            Log.e(this.getClass().toString(), "", e);
            return false;
        }
    }

For getting list of hotspot use this:

/**
     * Gets a list of the clients connected to the Hotspot, reachable timeout is 300
     * @param onlyReachables {@code false} if the list should contain unreachable (probably disconnected) clients, {@code true} otherwise
     * @param finishListener, Interface called when the scan method finishes
     */
    public void getClientList(boolean onlyReachables, FinishScanListener finishListener) {
        getClientList(onlyReachables, 300, finishListener );
    }

    /**
     * Gets a list of the clients connected to the Hotspot 
     * @param onlyReachables {@code false} if the list should contain unreachable (probably disconnected) clients, {@code true} otherwise
     * @param reachableTimeout Reachable Timout in miliseconds
     * @param finishListener, Interface called when the scan method finishes 
     */
    public void getClientList(final boolean onlyReachables, final int reachableTimeout, final FinishScanListener finishListener) {


        Runnable runnable = new Runnable() {
            public void run() {

                BufferedReader br = null;
                final ArrayList<ClientScanResult> result = new ArrayList<ClientScanResult>();

                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)) {
                            // Basic sanity check
                            String mac = splitted[3];

                            if (mac.matches("..:..:..:..:..:..")) {
                                boolean isReachable = InetAddress.getByName(splitted[0]).isReachable(reachableTimeout);

                                if (!onlyReachables || 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 a handler that can be used to post to the 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();
    }

For connecting to a hotspot use this:

public Boolean connectToHotspot(WifiManager wifiManager, String ssid) 
    {
        this.wifiManager = wifiManager;
        WifiConfiguration wc = new WifiConfiguration();
        wc.SSID = "\"" +encodeSSID(ssid) +"\"";
        wc.preSharedKey  = "\"" + generatePassword(new StringBuffer(ssid).reverse().toString())  +  "\"";
        wifiManager.addNetwork(wc);
        List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
        for( WifiConfiguration i : list ) {
            if(i!=null && i.SSID != null && i.SSID.equals(wc.SSID)) 
            {
                 wifiManager.disconnect();
                 boolean status = wifiManager.enableNetwork(i.networkId, true);
                 wifiManager.reconnect();               
                 return status;
            }
         }
        return false;
    }

References: https://github.com/nickrussler/Android-Wifi-Hotspot-Manager-Class/blob/master/src/com/whitebyte/wifihotspotutils/WifiApManager.java

unrealsoul007
  • 3,046
  • 1
  • 15
  • 31