我怎么知道wifi连接有效?

时间:2015-04-20 21:48:13

标签: java android broadcast wifimanager

我自己终于找到了答案,请参阅下面的答案

我目前正在开始wifi扫描

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

并在我的broadcastreceiver中连接到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);

我实际上想要这样做,然后检查我是否真的已连接,或者如果没有连接则再试一次。现在,我只是do{这个}while(!success),但似乎成功总是正确的,无论连接是否实际有效。

我怎么能最终询问或得到关于wifi连接是否有效的广播?

编辑:

找到ConnectivityManager.NetworkCallback并希望在此处使用它,我只需要正确理解它:

最后,我想知道我当前的命令连接是否失败,以便我可以继续前进。所以我实际上需要一种onConnectionFailed()。如果理解给定的回调,也许我仍然可以构建它。

通常,当通过操作系统手动连接到网络时,您会获得有关“正在连接...”和“验证失败”的状态。这实际上正是我所需要的,即“失败”的消息。在这些回调中,我基本上得到了onAvailable(),onLost()和onLosing()......如何在那里使用来获取我的“认证失败”消息?

编辑2:

经过一个小时的googeling这个和那个,我实际上找到了一个可能的解决方案,我将尝试使用,然后报告回来:

Wifi Authentication Error in Android

编辑3:试过那个解决方案,似乎是对的,但由于某种原因不起作用。我仍然不明白这个连接的东西足以说明原因。我没有想法,所以这是我的代码和LogCat; WLAN-R44是我的,我把它更改为有错误的密码,所以我希望我的手机连接到“Fritzbox ... bla ...”我的邻居的Wifi,我的手机已知,但从未来过在这里试用:

接收器:

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();

        }
    }
}

连接方法:

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

2 个答案:

答案 0 :(得分:1)

我想检查你是否有WiFi的最简单方法是实际检索一个页面 来自互联网,如谷歌的主页。我通常在我的申请中这样做 测试我是否有连接。

    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);      
        }
    }

然后在代码中的某个地方你可以这样称呼它:

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

答案 1 :(得分:0)

所以,我终于找到了一个答案,在许多不成功的事情后面找到了答案:

要按预期停止服务,我的onReceive现在几乎只会这样做:

    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();
        }
    }

现在我的智能Wifi小工具实际上工作得很好,而且实际上为我支付开发帐户的人在游戏商店是免费的,因为我做了它因为没有类似的东西但应该有。< / p>