简体   繁体   中英

Android: How to Scan WiFi, Connect to an AP and then Establish a TCP Connection?

I am writing an Android app. In my app, I want it to scan the WiFi network, and then connect to a dedicated Access Point (AP) by checking the SSID. And then after connected to the AP, establish a TCP connection to it.

Above I have described 3 tasks in order. I know how to do each task independently, however I do not know the proper way to finish them in sequence. Examples are appreciated.

Currently my code is to start scan the WiFi network whenever the user pressed a button by:

WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
if (wifiManager.isWifiEnabled() == false) {
    wifiManager.setWifiEnabled(true);
    Toast.makeText(MainActivity.this, "WiFi is enabled", Toast.LENGTH_SHORT).show();
}
wifiManager.startScan();

I used a broadcast receiver to check when the scanning finished, and then invoke a method ( ReconnectAP() ) to connect WiFi to the AP. I also used the broadcast receiver to check when it connected to the AP, then I want to execute an Async Task to establish the TCP network. However, by googling, I learn that it is a bad practice to execute async task in a broadcast receiver, because the async task can be killed by Android when the receiver finished.

private String networkSSID = "The_AP_SSID";

// In onCreate of MainActivity, register the broadcast receiver:
registerReceiver(WiFireceiver, new IntentFilter(
            WifiManager.NETWORK_STATE_CHANGED_ACTION));
registerReceiver(WiFireceiver, new IntentFilter(
            WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));

// Implement my broadcast receiver class:
BroadcastReceiver WiFireceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();

        if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(action)) {

            Log.d(TAG, "WiFiReceiver received broadcast, action is SCAN_RESULTS_AVAILABLE_ACTION");
            Log.d(TAG, "Start to check if need to reconnect to Charger AP");
            ReconnectAP();

        }

        if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(action)) {

            Log.d(TAG, "WiFiReceiver received broadcast, action is NETWORK_STATE_CHANGED_ACTION");

            NetworkInfo netInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
            // If the connection type is WiFi...
            if (netInfo != null && ConnectivityManager.TYPE_WIFI == netInfo.getType()) {

                // If it is connected now....
                if (netInfo.isConnected()) {

                    Log.d(TAG, "WiFi connected");

                    // Get WiFi connection information, eg SSID
                    WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
                    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                    String ssid = wifiInfo.getSSID();

                    Log.d(TAG, "WiFi connected SSID is : " + ssid);

                    if(ssid.equals(networkSSID)) {
                        // Start async task to establish a TCP connection:
                        new ConnectTCPAsynTask().execute();

                    }
                } else {
                    Log.d(TAG, "WiFi disconnected");
                }
            }
        }
    }
};

int ReconnectAP() {

    Log.d(TAG, "In ReconnectAP( )");

    wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
    String ssid = wifiInfo.getSSID();

    Log.d(TAG, "Original connected AP SSID: " + ssid);

    if (!ssid.equals(networkSSID)) {

        Log.d(TAG, "It is not equal to the dedicated AP SSID, 
                    we will disconnect the current WiFi connection, 
                    and then connect to our dedicate AP");

        List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
        for (WifiConfiguration i : list) {
            if (i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"")) {

                Log.d(TAG, "Start disconnect and reconnect to " + networkSSID);
                wifiManager.disconnect();
                wifiManager.enableNetwork(i.networkId, true);
                wifiManager.reconnect();

                return 1;
            }
        }
        Log.d(TAG,"Reach here if cannot find the target SSID");
        return -1;
    }
    Log.d(TAG, "Reach here if we already connected to the dedicated AP");
    return 0;

}

将标志从广播接收器传递回主要活动,并让主要活动处理任务。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM