Android API连接到Wifi网络 [英] Android API to Connect to Wifi Network

查看:204
本文介绍了Android API连接到Wifi网络的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对WiFi API的版本完全迷失了.我想以编程方式连接到已配置的WiFi网络.正如在这个问题中所描述的:以编程方式连接到Android的wifi网络

I'm totaly lost in the versions of WiFi APIs. I want to connect to a configured WiFi Network programmaticaly. As decribed in this question: Connect to wifi network Android programmatically

我在Android 10上进行开发,希望编写与旧版Android版本兼容的代码.

I develop on Android 10 and want to write a code that is also compatible with older Android Versions.

在我的android 10上,所描述的代码不起作用.在Android 10上实现该功能需要什么代码?

On my android 10 the code described does not work. What code do I need to implement the functionality on Android 10?

如何编写也可以在其他Android 9手机上运行的应用程序?

What do I do to write an application that also runs on my other Android 9 phone?

关于于尔根(Jürgen)

Regards Jürgen

推荐答案

在Android Q中,连接到Wifi网络有很多变化.

From Android Q, connecting to Wifi Network has changes a lot.

您正在使用的所有代码或提到的@matdev首先使用 WifiManager 中的API public int addNetwork(WifiConfiguration配置),并将返回-1作为networkID.

First of all the code you are using or @matdev mentioned uses API public int addNetwork (WifiConfiguration config) from WifiManager is deprecated in Android 10 and will return -1 as networkID.

从Android Q开始,建议使用两个类进行Wifi连接.但是它们每个都有自己的优点和缺点.

From Android Q, two classes are suggested for Wifi connection. But each of them has its own advantage and disadvantage.

1. WifiNetworkSpecifier

WifiUtil库中的代码示例

A code example from WifiUtil Library

WifiNetworkSpecifier.Builder wifiNetworkSpecifierBuilder = new WifiNetworkSpecifier.Builder()
            .setSsid(scanResult.SSID)
            .setBssid(MacAddress.fromString(scanResult.BSSID));

    final String security = ConfigSecurities.getSecurity(scanResult);

    ConfigSecurities.setupWifiNetworkSpecifierSecurities(wifiNetworkSpecifierBuilder, security, password);


    NetworkRequest networkRequest = new NetworkRequest.Builder()
            .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
            .setNetworkSpecifier(wifiNetworkSpecifierBuilder.build())
            .build();

    // not sure, if this is needed
    if (networkCallback != null) {
        connectivityManager.unregisterNetworkCallback(networkCallback);
    }

    networkCallback = new ConnectivityManager.NetworkCallback() {
        @Override
        public void onAvailable(@NonNull Network network) {
            super.onAvailable(network);

            wifiLog("AndroidQ+ connected to wifi ");

            // bind so all api calls are performed over this new network
            connectivityManager.bindProcessToNetwork(network);
        }

        @Override
        public void onUnavailable() {
            super.onUnavailable();

            wifiLog("AndroidQ+ could not connect to wifi");
        }
    };

    connectivityManager.requestNetwork(networkRequest, networkCallback);

我对该实现的观察是-这更像是P2P通信,并且此时来自同一设备的其他应用程序无法使用所连接的WiFi网络的互联网

My observation with this implementation is - It is more like P2P communication, and at this time other application from the same device cannot use internet from the connected WiFi network

2. WifiNetworkSuggestion 

developer.android.com中的代码示例

A code example from developer.android.com

final WifiNetworkSuggestion suggestion1 =
  new WifiNetworkSuggestion.Builder()
  .setSsid("test111111")
  .setIsAppInteractionRequired(true) // Optional (Needs location permission)
  .build();

final WifiNetworkSuggestion suggestion2 =
  new WifiNetworkSuggestion.Builder()
  .setSsid("test222222")
  .setWpa2Passphrase("test123456")
  .setIsAppInteractionRequired(true) // Optional (Needs location permission)
  .build();

final WifiNetworkSuggestion suggestion3 =
  new WifiNetworkSuggestion.Builder()
  .setSsid("test333333")
  .setWpa3Passphrase("test6789")
  .setIsAppInteractionRequired(true) // Optional (Needs location permission)
  .build();

final PasspointConfiguration passpointConfig = new PasspointConfiguration();
// configure passpointConfig to include a valid Passpoint configuration

final WifiNetworkSuggestion suggestion4 =
  new WifiNetworkSuggestion.Builder()
  .setPasspointConfig(passpointConfig)
  .setIsAppInteractionRequired(true) // Optional (Needs location permission)
  .build();

final List<WifiNetworkSuggestion> suggestionsList =
  new ArrayList<WifiNetworkSuggestion> {{
    add(suggestion1);
    add(suggestion2);
    add(suggestion3);
    add(suggestion4);
  }};

final WifiManager wifiManager =
  (WifiManager) context.getSystemService(Context.WIFI_SERVICE);

final int status = wifiManager.addNetworkSuggestions(suggestionsList);
if (status != WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS) {
// do error handling here…
}

// Optional (Wait for post connection broadcast to one of your suggestions)
final IntentFilter intentFilter =
  new IntentFilter(WifiManager.ACTION_WIFI_NETWORK_SUGGESTION_POST_CONNECTION);

final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
  @Override
  public void onReceive(Context context, Intent intent) {
    if (!intent.getAction().equals(
      WifiManager.ACTION_WIFI_NETWORK_SUGGESTION_POST_CONNECTION)) {
      return;
    }
    // do post connect processing here...
  }
};
context.registerReceiver(broadcastReceiver, intentFilter);

我对上述实现的观察是,当您调用 wifiManager.addNetworkSuggestions 时,它将返回成功并向用户显示连接通知.如果用户接受,则设备将连接到WiFi网络,其他应用程序可以连接互联网.但是,如果用户断开网络连接,然后再次调用 wifiManager.addNetworkSuggestions ,它将返回 WifiManager.STATUS_NETWORK_SUGGESTIONS_ERROR_ADD_DUPLICATE 错误.

My observation with the above mentioned implementation is, when you call the wifiManager.addNetworkSuggestions it return success and show user a notification for connection. If the user accept, device gets connected to the WiFi network and other app can user internet. But if user disconnect from network and you call wifiManager.addNetworkSuggestions again, it will return WifiManager.STATUS_NETWORK_SUGGESTIONS_ERROR_ADD_DUPLICATE error.

该API似乎仅提供设备可以自动连接的网络的建议列表.但是连接将由操作系统决定.

It looks like this API just provide a suggestion list of networks where the device can auto connect. But the connection will be determined by the OS.

但是,如果您确实需要解决方案,可以使用未记录的方式使用Android Source中的默认Wifi QR码扫描仪,该方法可以同时检测QR Code方案Zxing和DPP.

But if you really need a solution, an undocumented way use to the Default Wifi QR Code Scanner from Android Source that can detect both QR Code schems Zxing and DPP.

这是一个代码示例:

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if(requestCode == REQUEST_CODE_WIFI_QR_SCANNER && resultCode == RESULT_OK)
    {
        //WIFI Connection is Successful
    }
    else
    {
        //.......
    }
}

@RequiresApi(api = Build.VERSION_CODES.Q)
private void startWifiQRCodeScanner(Context context)
{
    final String INTENT_ACTION_WIFI_QR_SCANNER = "android.settings.WIFI_DPP_ENROLLEE_QR_CODE_SCANNER";
    WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);

    if(wifiManager.isEasyConnectSupported())
    {
        final Intent intent = new Intent(INTENT_ACTION_WIFI_QR_SCANNER);
        startActivityForResult(intent, REQUEST_CODE_WIFI_QR_SCANNER);
    }
}

这篇关于Android API连接到Wifi网络的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆