• Wifi列表扫描和Wifi链接


     上面的截图,就是本文要介绍的主要功能。

     1.准备工作,声明权限:

    1. <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    2. <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    3. <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    4. <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    5. <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    6. <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
    7. <uses-permission android:name="android.permission.WRITE_SETTINGS"
    8. tools:ignore="ProtectedPermissions" />

    2.打开WIfi

        1)申请权限:注意的一点就是,打开wifi需要申请位置权限

    1. String[] permsLocation = {"android.permission.ACCESS_WIFI_STATE"
    2. , "android.permission.CHANGE_WIFI_STATE"
    3. , "android.permission.ACCESS_COARSE_LOCATION"
    4. , "android.permission.ACCESS_FINE_LOCATION"};
    1. //获取权限
    2. private void getPerMission() {
    3. mPermissionsChecker = new PermissionsChecker(MainActivity.this);
    4. if (mPermissionsChecker.lacksPermissions(permsLocation)) {
    5. ActivityCompat.requestPermissions(MainActivity.this, permsLocation, 1000);
    6. }
    7. }

      2)打开wifi

         获取WifiManager:

     wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
    1. public boolean openWifi(WifiManager mWifiManager) {
    2. boolean bRet = true;
    3. Log.e("nyz", "wifi enable " + mWifiManager.isWifiEnabled());
    4. //android Q 不能使用,只能跳转设置界面,手动开启。startActivity(Intent(Settings.ACTION_WIFI_SETTINGS))
    5. if (!mWifiManager.isWifiEnabled()) {
    6. bRet = mWifiManager.setWifiEnabled(true);
    7. }
    8. Log.e("nyz", "wifi result " + bRet);
    9. return bRet;
    10. }

      需要注意的一点就是,Android10以上下面的打开Wifi的功能将会失效,需要跳转到设置界面,由用户手动打开。

    1. * @deprecated Starting with Build.VERSION_CODES#Q, applications are not allowed to
    2. * enable/disable Wi-Fi.
    3. * Compatibility Note: For applications targeting
    4. * {@link android.os.Build.VERSION_CODES#Q} or above, this API will always return {@code false}
    5. * and will have no effect. If apps are targeting an older SDK (
    6. * {@link android.os.Build.VERSION_CODES#P} or below), they can continue to use this API.
    7. */
    8. @Deprecated
    9. public boolean setWifiEnabled(boolean enabled) {
    10. try {
    11. return mService.setWifiEnabled(mContext.getOpPackageName(), enabled);
    12. } catch (RemoteException e) {
    13. throw e.rethrowFromSystemServer();
    14. }
    15. }

    3.获取WIfi列表:

        1)创建一个BroadCastReceiver:

           收到 WifiManager.SCAN_RESULTS_AVAILABLE_ACTION 广播后,可以获取WIfi列表

    1. class WifiReceiver extends BroadcastReceiver {
    2. @Override
    3. public void onReceive(Context context, Intent intent) {
    4. if (TextUtils.isEmpty(intent.getAction())) {
    5. return;
    6. }
    7. String action = intent.getAction();
    8. Log.e("nyz", "action " + action);
    9. if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(action)) {
    10. boolean result = intent.getBooleanExtra(WifiManager.EXTRA_RESULTS_UPDATED, false);
    11. List<ScanResult> wifiList = wifiManager.getScanResults();
    12. Log.e("nyz", "results " + wifiList.size() + " result " + result);
    13. if (wifiList != null) {
    14. for (int i = 0; i < wifiList.size(); i++) {
    15. ScanResult wifi = wifiList.get(i);
    16. if (TextUtils.isEmpty(wifi.SSID)) {
    17. continue;
    18. }
    19. Log.e("nyz", "BSSID " + wifi.BSSID);
    20. Log.e("nyz", "SSID " + wifi.SSID);
    21. Log.e("nyz", "level " + wifi.level);
    22. Log.e("nyz", "capabilities " + wifi.capabilities);
    23. //拿到结果后,可以更新界面,在界面展示
    24. }
    25. }
    26. } else if (WifiManager.ACTION_WIFI_NETWORK_SUGGESTION_POST_CONNECTION.equals(action)) {
    27. } else if (ConnectivityManager.CONNECTIVITY_ACTION.equals(action)) {
    28. }
    29. }
    30. }

      2)注册和反注册:

    1. private void registerReceiver() {
    2. wifiReceiver = new WifiReceiver();
    3. IntentFilter filter = new IntentFilter();
    4. filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
    5. filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
    6. filter.addAction(WifiManager.ACTION_WIFI_NETWORK_SUGGESTION_POST_CONNECTION);
    7. registerReceiver(wifiReceiver, filter);
    8. }
    9. @Override
    10. protected void onDestroy() {
    11. super.onDestroy();
    12. unregisterReceiver(wifiReceiver);
    13. }

      3)开始扫描Wifi:

          调用  wifiManager.startScan();开始扫描。搜索到附近的Wifi后,系统会发布广播,可以在广播接收者中,收到wifi列表信息。

    1. findViewById(R.id.scan).setOnClickListener(v -> {
    2. if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
    3. ActivityCompat.requestPermissions(MainActivity.this, permsLocation, 1000);
    4. return;
    5. }
    6. boolean result = wifiManager.startScan();
    7. Log.e("nyz", "result " + result);
    8. List<ScanResult> wifiList = wifiManager.getScanResults();
    9. Log.e("nyz", "size " + wifiList.size());
    10. // if (wifiList != null) {
    11. // for (int i = 0; i < wifiList.size(); i++) {
    12. // ScanResult wifi = wifiList.get(i);
    13. // Log.e("nyz", "BSSID " + wifi.BSSID);
    14. // Log.e("nyz", "SSID " + wifi.SSID);
    15. // Log.e("nyz", "level " + wifi.level);
    16. // Log.e("nyz", "capabilities " + wifi.capabilities);
    17. // }
    18. // }
    19. WifiInfo wifiInfo = wifiManager.getConnectionInfo();
    20. Log.e("nyz", "wifiInfo = " + (wifiInfo == null));
    21. });

    4.链接wifi:   

    1. private void connWifi(Context context, String ssid, String pwd) {
    2. if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
    3. return;
    4. }
    5. Log.e("nyz", "sdk " + Build.VERSION.SDK_INT);
    6. if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
    7. WifiConfiguration config = createWifiInfo(ssid, pwd);
    8. int netId = wifiManager.addNetwork(config);
    9. Log.e("nyz", "netID " + netId);
    10. boolean isConn = wifiManager.enableNetwork(netId, true);
    11. Log.e("nyz", "isConn " + isConn);
    12. } else {
    13. // connectSuggestion(ssid, pwd);
    14. connectSpecifier(ssid, pwd);
    15. }
    16. }

              在Android10以前,可以通过addNetwork的方式进行链接,在Android10以后,这种方式就不推荐使用了。

       

    1. * @deprecated
    2. * a) See {@link WifiNetworkSpecifier.Builder#build()} for new
    3. * mechanism to trigger connection to a Wi-Fi network.
    4. * b) See {@link #addNetworkSuggestions(List)},
    5. * {@link #removeNetworkSuggestions(List)} for new API to add Wi-Fi networks for consideration
    6. * when auto-connecting to wifi.
    7. * <b>Compatibility Note:b> For applications targeting
    8. * {@link android.os.Build.VERSION_CODES#Q} or above, this API will always return {@code -1}.
    9. */
    10. @Deprecated
    11. public int addNetwork(WifiConfiguration config) {
    12. if (config == null) {
    13. return -1;
    14. }
    15. config.networkId = -1;
    16. return addOrUpdateNetwork(config);
    17. }

      Android10以后链接wifi:

        1)建议的方式:

         官方文档:适用于互联网连接的 WLAN 建议 API  |  Android 开发者  |  Android Developers

    1. @RequiresApi(api = Build.VERSION_CODES.Q)
    2. private void connectSuggestion(String ssid, String pwd) {
    3. WifiNetworkSuggestion suggestion2 =
    4. new WifiNetworkSuggestion.Builder()
    5. .setSsid(ssid)
    6. .setWpa2Passphrase(pwd)
    7. //是否可以接收到android.net.wifi.action.WIFI_NETWORK_SUGGESTION_POST_CONNECTION
    8. .setIsAppInteractionRequired(true)
    9. .build();
    10. List<WifiNetworkSuggestion> suggestionsList = new ArrayList<WifiNetworkSuggestion>();
    11. suggestionsList.add(suggestion2);
    12. int status = wifiManager.addNetworkSuggestions(suggestionsList);
    13. Log.e("nyz", "status " + status);
    14. if (status != WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS) {
    15. }
    16. }

       2)点对点的方式:

    官方文档:WifiNetworkSpecifier  |  Android Developers

    1. @RequiresApi(api = Build.VERSION_CODES.Q)
    2. private void connectSpecifier(String ssid, String pwd) {
    3. WifiNetworkSpecifier specifier = new WifiNetworkSpecifier.Builder()
    4. .setSsidPattern(new PatternMatcher(ssid, PatternMatcher.PATTERN_PREFIX))
    5. .setWpa2Passphrase(pwd).build();
    6. NetworkRequest request = new NetworkRequest.Builder()
    7. .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
    8. .setNetworkSpecifier(specifier)
    9. .build();
    10. ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    11. manager.requestNetwork(request, new ConnectivityManager.NetworkCallback() {
    12. @Override
    13. public void onAvailable(@NonNull Network network) {
    14. super.onAvailable(network);
    15. Log.e("nyz", "onAvailable");
    16. if (network != null) {
    17. }
    18. }
    19. @Override
    20. public void onUnavailable() {
    21. super.onUnavailable();
    22. Log.e("nyz", "onUnavailable");
    23. }
    24. @Override
    25. public void onCapabilitiesChanged(@NonNull Network network, @NonNull NetworkCapabilities networkCapabilities) {
    26. super.onCapabilitiesChanged(network, networkCapabilities);
    27. Log.e("nyz", "网络变化");
    28. }
    29. });
    30. }

  • 相关阅读:
    Flutter组件-Material属性
    使用 Django 创建 App
    node_exporter无法启动处理
    【教程】Autojs使用OpenCV进行SIFT/BRISK等算法进行图像匹配
    JSON Schema的应用(具体的使用场景)
    M的编程备忘录之Linux——基础开发工具
    【源码解读】VUE2.0和VUE3.0响应式区别?
    Pandas:如何让你的代码性能飙升
    Java之旅--Linux&java进阶(看清操作系统层面的事)
    利用Nginx正向代理实现局域网电脑访问外网
  • 原文地址:https://blog.csdn.net/niuyongzhi/article/details/133770365