Java 我如何知道wifi连接工作正常?

Java 我如何知道wifi连接工作正常?,java,android,broadcast,wifimanager,Java,Android,Broadcast,Wifimanager,终于自己找到了答案,请参见下面的我的答案 我现在开始wifi扫描 wifiReceiver = new WifiReceiver(); registerReceiver(wifiReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)); wifiManager.startScan(); 在我的广播接收器中,连接到wifi class WifiReceiver extends Broadc

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

我现在开始wifi扫描

    wifiReceiver = new WifiReceiver();
    registerReceiver(wifiReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
    wifiManager.startScan();
在我的广播接收器中,连接到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()部分:

我真的想这样做,然后检查我是否真的连接了,或者如果没有,再试一次。现在,我只是在(!success)时做{这个
},但不管连接是否实际工作,成功似乎总是正确的

最后,我如何询问或获得有关wifi连接是否工作的广播

编辑:

找到了
ConnectivityManager.NetworkCallback
并想在这里使用它,我只需要正确理解它:

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

通常,当通过操作系统手动连接到网络时,您会得到关于“连接…”和“身份验证失败”的更新状态。这正是我需要的,那个“失败”的信息。在这些回调中,我基本上得到了onAvailable()、onLost()和onLosing()…如何使用它们来获取我的“身份验证失败”消息

编辑2:

在谷歌搜索了一个小时后,我实际上找到了一个可能的解决方案,我将尝试利用它,然后报告:

编辑3:尝试过该解决方案,似乎是正确的,但由于某些原因不起作用。我仍然不太明白这一点,不知道为什么。我没有主意了,这是我的代码和日志;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;
}

我想检查你是否有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);      
        }
    }

因此,在经历了许多不成功的事情之后,我终于找到了答案:

要按预期停止服务,我的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小部件实际上工作得很好,而且有人真的为我支付了开发帐户的费用,它在play store上是免费的,我之所以这样做,是因为没有类似的东西,但应该有。

你可以注册这个库,在连接和断开连接时获得回调,或者只是查看它的代码,了解它是如何工作的,通过它挖掘并找到我可能需要使用的核心内容。更新了我的问题,因为我仍然不知道如何使用它来获得我想要的结果……嗯,这样做怎么样:这可能不会正常工作,除非我让我的
服务
睡眠几秒钟,然后问它是否有效。我的目标是一个回调解决方案,因为我希望我的服务尽快
stopSelf()
,有时连接到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();
    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();
        }
    }