当前位置:   article > 正文

Android WIFI连接总结

android wifi连接

1、setWifiEnable无效?

        WifiManager.setWifiEnable(true/false)在10以后都没有作用,一直会返回false,可以将targetSdk版本设置到28,可以触发权限判断

 

2、Android 10、11、12控制连接指定WIFI

自己尝试下来不root有两种办法

        1、建议式连接

                

  1. val suggestion = WifiNetworkSuggestion.Builder()
  2. .setSsid(“指定wifi的SSID,就是wifi的名字”)
  3. .setWpa2Passphrase(“WIFI密码”)
  4. .setIsAppInteractionRequired(true)
  5. .build()
  6. val suggestionsList = listOf(suggestion)
  7. val status = wifiManager.addNetworkSuggestions(suggestionsList)
  8. Log.d(TAG, status.toString())
  9. if (status != WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS) {
  10. }
  11. val intentFilter = IntentFilter(WifiManager.ACTION_WIFI_NETWORK_SUGGESTION_POST_CONNECTION);
  12. val broadcastReceiver = object : BroadcastReceiver() {
  13. override fun onReceive(context: Context, intent: Intent) {
  14. if (!intent.action.equals(WifiManager.ACTION_WIFI_NETWORK_SUGGESTION_POST_CONNECTION)) {
  15. return
  16. }
  17. }
  18. };
  19. context.registerReceiver(broadcastReceiver, intentFilter);

                实际操作下来,并没有什么卵用,当设置里连接过wifi,你的建议Android不听

        2、P2P连接方式

        PS:谷歌官方示例里的这句话不要加,在荣耀手机加了无法连接,其他手机没试
            //.removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)

                

  1. val specifier = WifiNetworkSpecifier.Builder()
  2. .setSsidPattern(PatternMatcher("WIFI名字", PatternMatcher.PATTERN_PREFIX))
  3. .setWpa2Passphrase("密码")
  4. .build()
  5. val request = NetworkRequest.Builder()
  6. .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
  7. //谷歌官方示例里的这句话不要加,在荣耀手机加了无法连接,其他手机没试
  8. //.removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
  9. .setNetworkSpecifier(specifier)
  10. .build()
  11. val connectivityManager = getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager
  12. val networkCallback = object : ConnectivityManager.NetworkCallback() {
  13. override fun onAvailable(network: Network) {
  14. Log.e(TAG, "onAvailable")
  15. }
  16. override fun onUnavailable() {
  17. Log.e(TAG, "onUnavailable")
  18. }
  19. }
  20. connectivityManager.requestNetwork(request, networkCallback)

        连接下来还是挺顺畅的,就是连上以后系统WIFI不会进行记录,并且出现其他app不能联网的情况,高版本的还是老老实实的自己跳WIFI设置吧

       

startActivity(Intent(Settings.ACTION_WIFI_SETTINGS))

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/295462
推荐阅读
相关标签
  

闽ICP备14008679号