简体   繁体   中英

How do I know the wifi connection worked?

Finally found an answer myself, see my answer below

I currently start a wifi scan

    wifiReceiver = new WifiReceiver();
    registerReceiver(wifiReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
    wifiManager.startScan();

and in my broadcastreceiver connect to a wifi

class WifiReceiver extends BroadcastReceiver{
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.e("DEBUG", "Wifi scanned");
        SmartWifiChange(); //connect to certain wifi if stuff.
        unregisterReceiver(this);
        stopSelf(); //end of a running service
    }
}

SmartWifiChange() partial:

        WifiConfiguration wifiToConnect = presentWifis.get(resultToConnect);
        success = wifiManager.enableNetwork(wifiToConnect.networkId, true);
        if(success)
            Toast.makeText(getApplicationContext(), "Now connected to: "
            +resultToConnect.SSID,Toast.LENGTH_LONG).show();
        else presentWifis.remove(resultToConnect);

I actually want to do this and then check if I'm actually connected, or try again if it didn't. Right now, I'm just do{ ing this }while(!success) , but it seems success is always true, wether or not the connection actually worked.

How can I, in the end, ask or get a broadcast about wether or not the wifi connection worked?

Edit:

Found the ConnectivityManager.NetworkCallback and would like to use it here, I just need to understand it properly:

In the end, I want to know if my currently commanded connection failed so I can move on. So I actually need kind of an onConnectionFailed(). Maybe I could still build that, if understand the given callbacks.

Usually, when manually connecting to a network via OS, you get status updated about "connecting..." and "authentification failed". That's actually exactly what I need, that "failed" message. On these Callbacks I essentially got onAvailable(), onLost() and onLosing()...how to use there to get my "authentification failed" message?

Edit 2:

After an hour of googeling this and that, I actually found a possible solution, which I will try to utilize and then report back:

Wifi Authentication Error in Android

Edit 3: Tried that solution, seems right but doesn't work for some reason. I still don't understand this connecting thing enough to say why. I'm out of ideas, so here's my code and LogCat; WLAN-R44 is mine, I changed it to have a wrong password and so wanted my phone to get connected to the "Fritzbox...bla..." Wifi of my neighbor, which is known to my phone, but never even comes up for trial here:

Receiver:

class WifiReceiver extends BroadcastReceiver{
    @Override
    public void onReceive(Context context, Intent intent) {

        switch(intent.getAction()) {
            case WifiManager.SCAN_RESULTS_AVAILABLE_ACTION:
                Log.e("DEBUG", "Wifi scanned");
                unregisterReceiver(this);
                if(SmartWifiChange(true)){
                    registerReceiver(this, new IntentFilter(WifiManager
                            .SUPPLICANT_STATE_CHANGED_ACTION));
                }else {
                    Log.e("Debug", "Off");
                    stopSelf();
                }
                break;
            case WifiManager.SUPPLICANT_STATE_CHANGED_ACTION:
                Log.e("Debug", "State changed action");
                Log.e("Debug", "New state: "+intent.getParcelableExtra(WifiManager
                        .EXTRA_NEW_STATE).toString());
                if (intent.getIntExtra(WifiManager.EXTRA_SUPPLICANT_ERROR, -1)==WifiManager.ERROR_AUTHENTICATING)
                    Log.e("Debug", "Error authenticating");
                    if (!SmartWifiChange(false)){
                        unregisterReceiver(this);
                        Log.e("AfterError", "Off");
                        stopSelf();
                    }
                else if ((intent.getParcelableExtra(WifiManager
                        .EXTRA_NEW_STATE))==SupplicantState.COMPLETED){
                        Log.e("Debug", "Completed");
                    Toast.makeText(context, "Done", Toast.LENGTH_LONG).show();
                    unregisterReceiver(this);
                        Log.e("Completed", "Off");
                    stopSelf();
                }else{
                        Toast.makeText(context, "Problem", Toast.LENGTH_SHORT).show();
                        Log.e("Problem", intent.getParcelableExtra(WifiManager
                            .EXTRA_NEW_STATE).toString());
                        Log.e("Problem", "Off");
                        unregisterReceiver(this);
                        stopSelf();
                }
                break;
            default:
                stopSelf();

        }
    }
}

Connection method:

private boolean SmartWifiChange(boolean success) {
    boolean connectToWifi = true;
    parseWifis();

        //Keine bekannten Wifis vorhanden
        if (presentWifis.isEmpty()){
            wifiManager.setWifiEnabled(false); //WLAN aus
            Toast.makeText(getApplicationContext(), "No known Wifis -> mobile data",
                    Toast.LENGTH_LONG).show();
            setMobileData(true);//Datenverbindung an
            connectToWifi=false;
        }else{
            if(success) {
                ScanResult[] keysArray = presentWifis.keySet().toArray(new ScanResult[presentWifis
                        .keySet().size()]);
                resultToConnect = keysArray[0];
                for (int i = 1; i < presentWifis.size(); i++) {
                    if (keysArray[i].level > resultToConnect.level) {
                        resultToConnect = keysArray[i];
                    }
                }
                WifiConfiguration wifiToConnect = presentWifis.get(resultToConnect);
                wifiManager.enableNetwork(wifiToConnect.networkId, true);
                Toast.makeText(getApplicationContext(), "Now connecting to: " + resultToConnect
                                .SSID,
                        Toast.LENGTH_SHORT).show();
                Log.e("Debug", resultToConnect.SSID);
            }
            else {
                Log.e("Debug", "Neuer Versuch");
                presentWifis.remove(resultToConnect);
                connectToWifi=SmartWifiChange(true);
            }
            if(connectToWifi)
                setMobileData(false);
        }
    return connectToWifi;
}

LogCat:

04-21 15:39:30.025  16243-16243/de.regenhardt.smartwifiwidget E/DEBUG﹕ Service started
04-21 15:39:30.057  16243-16243/de.regenhardt.smartwifiwidget E/TextView﹕ get resource from application failed.
04-21 15:39:32.828  16243-16243/de.regenhardt.smartwifiwidget E/DEBUG﹕ Wifi scanned
04-21 15:39:33.105  16243-16243/de.regenhardt.smartwifiwidget E/TextView﹕ get resource from application failed.
04-21 15:39:33.230  16243-16243/de.regenhardt.smartwifiwidget E/Debug﹕ WLAN-R44
04-21 15:39:33.237  16243-16243/de.regenhardt.smartwifiwidget E/DEBUG﹕ Data: false
04-21 15:39:33.244  16243-16243/de.regenhardt.smartwifiwidget E/Debug﹕ State changed action
04-21 15:39:33.245  16243-16243/de.regenhardt.smartwifiwidget E/Debug﹕ New state: FOUR_WAY_HANDSHAKE
04-21 15:39:33.263  16243-16243/de.regenhardt.smartwifiwidget E/Debug﹕ Neuer Versuch
04-21 15:39:33.280  16243-16243/de.regenhardt.smartwifiwidget E/TextView﹕ get resource from application failed.
04-21 15:39:33.285  16243-16243/de.regenhardt.smartwifiwidget E/Debug﹕ WLAN-R44
04-21 15:39:33.285  16243-16243/de.regenhardt.smartwifiwidget E/DEBUG﹕ Data: false
04-21 15:39:33.286  16243-16243/de.regenhardt.smartwifiwidget E/DEBUG﹕ Data: false
04-21 15:39:33.288  16243-16243/de.regenhardt.smartwifiwidget E/TextView﹕ get resource from application failed.
04-21 15:39:33.291  16243-16243/de.regenhardt.smartwifiwidget E/Problem﹕ FOUR_WAY_HANDSHAKE
04-21 15:39:33.291  16243-16243/de.regenhardt.smartwifiwidget E/Problem﹕ Off

I guess the simplest way to check if you have WiFi is to actually retrieve a page from the internet like Google's main page. I normally do this in my application to test if I have a connection or not.

    class TestConnectionTask extends AsyncTask<Void, Void, Boolean>
    {
        private String mUrl;

        public TestConnectionTask(String url)
        {
          this.mUrl = url;
        }

        @Override
        protected Boolean doInBackground(Void... params)
        {
          try
          {
            URL urlConnection = new URL(mUrl);
            HttpURLConnection connection = (HttpURLConnection) urlConnection
              .openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();

            return Boolean.TRUE;
          }
          catch (Exception e)
          {
            e.printStackTrace();
          }
          return null;
        }

        @Override
        protected void onPostExecute(Boolean result)
        {
          if ( result != null)
          {
            // Connection was successful
            // Do something here
          }
          super.onPostExecute(result);      
        }
    }

and then somewhere in your code you can call it as such:

new TestConnectionTask("http://www.google.com").execute();

So, I finally found an answer, aftertrying many unsuccessful things:

To stop the Service as intended, my onReceive pretty much only does this now:

    public void onReceive(Context context, Intent intent) {
        Log.e("DEBUG", "Received");
        try {
            switch(intent.getAction()) {
                case WifiManager.SUPPLICANT_STATE_CHANGED_ACTION:
                    Log.e("Debug", "State changed action");
                    Log.e("Debug", "New state: "+intent.getParcelableExtra(WifiManager
                            .EXTRA_NEW_STATE).toString());
                    if (intent.getIntExtra(WifiManager.EXTRA_SUPPLICANT_ERROR, -1)==WifiManager.ERROR_AUTHENTICATING) {
                        Log.e("Debug", "Error authenticating");
                        if (!SmartWifiChange(false)) { //retry with next available Wifi
                            unregisterReceiver(this);
                            Log.e("AfterError", "Off");
                            stopSelf();
                        }
                    }
                    else if ((intent.getParcelableExtra(WifiManager
                            .EXTRA_NEW_STATE))==SupplicantState.COMPLETED){
                            Log.e("Debug", "Completed");
                        Toast.makeText(context, "Done", Toast.LENGTH_LONG).show();
                        unregisterReceiver(this);
                            Log.e("Completed", "Off");
                        stopSelf();
                    }
                    break;
                default:
                    stopSelf();

            }
        } catch (Exception e) {
            e.printStackTrace();
            unregisterReceiver(this);
            stopSelf();
        }
    }

Now my Smart Wifi Widget actually works great, and as of somebody actually paying for a dev account for me it's for free on the play store, as I made it because there wasn't anything like it but there should be.

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