Android 在APP内、应用内 连接WiFi

2019-04-22  本文已影响0人  稻壳_互联网创变者

Android 在应用内连接特定的WiFi

首先需要在AndroidManifext.xml中添加以下权限

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> <!-- for Android 6 and above -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> <!-- for Android 6 and above -->

通过如下代码,可以实现连接到这个ssid的WiFi

String ssid = "work.dookay.com";
String key = "1q23l_yc45j_";

WifiConfiguration wifiConfig = new WifiConfiguration();
wifiConfig.SSID = String.format("\"%s\"", ssid);
wifiConfig.preSharedKey = String.format("\"%s\"", key);

 WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
 int netId = wifiManager.addNetwork(wifiConfig);
wifiManager.disconnect();
 wifiManager.enableNetwork(netId, true);
 wifiManager.reconnect();

启用WiFi

 WifiUtils.withContext(getApplicationContext()).enableWifi(this::checkResult);
 
  private void checkResult(boolean isSuccess)
  {
       if (isSuccess)
           Toast.makeText(MainActivity.this, "WIFI ENABLED", Toast.LENGTH_SHORT).show();
       else
           Toast.makeText(MainActivity.this, "COULDN'T ENABLE WIFI", Toast.LENGTH_SHORT).show();
  }

启用WiFi且无需回调的方式:

 WifiUtils.withContext(getApplicationContext()).enableWifi();

禁用WiFi

WifiUtils.withContext(getApplicationContext()).disableWifi();

扫描可用WiFi

WifiUtils.withContext(getApplicationContext()).scanWifi(this::getScanResults).start();

private void getScanResults(@NonNull final List<ScanResult> results)
{
    if (results.isEmpty())
    {
        Log.i(TAG, "SCAN RESULTS IT'S EMPTY");
        return;
    }
    Log.i(TAG, "GOT SCAN RESULTS " + results);
}

连接WiFi

你必须知道这个WiFi的SSID和WPA/WPS2密钥

 WifiUtils.withContext(getApplicationContext())
                        .connectWith("YourWiFi", "YourWiFiPassword")
                        .onConnectionResult(this::checkResult)
                        .start();

  private void checkResult(boolean isSuccess)
  {
        if (isSuccess)
            Toast.makeText(MainActivity.this, "CONNECTED YAY", Toast.LENGTH_SHORT).show();
        else
            Toast.makeText(MainActivity.this, "COULDN'T CONNECT", Toast.LENGTH_SHORT).show();
  }

取消正在连接

有两种方式:

WifiUtils.withContext(getApplicationContext())
                     .connectWith("YourWiFi", "YourWiFiPassword")
                     .setTimeout(15000) //15秒
                     .onConnectionResult(this::checkResult)
                     .start();
 WifiConnectorBuilder.WifiUtilsBuilder builder = WifiUtils.withContext(getApplicationContext());
 builder.connectWith("YourWiFi", "YourWiFiPassword")
 .onConnectionResult(this::checkResult)
 .start();
 builder.cancelAutoConnect();
上一篇下一篇

猜你喜欢

热点阅读