Android 9.0以上 连接wifi失败 解决方案
Android9开始,WIFI那块的API发生了改变:
addNetwork(WifiConfiguration config)
此方法在API级别Q中已弃用)
见addNetworkSuggestions(java.util.List), removeNetworkSuggestions(java.util.List)新的API添加Wi-Fi网络进行审议时,自动连接到无线网络。 兼容性注意:对于目标Build.VERSION_CODES.Q或更高的应用程序 ,此API将始终返回-1。
废话不多说直接上代码:
首先需要在清单文件中添加权限:
其次需要再activity动态申请权限,代码如下:
public class MainActivity extends AppCompatActivity {
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION};
@Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); verifyStoragePermissions(MainActivity.this); findViewById(R.id.but1).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { test("ssid","密码"); } }); findViewById(R.id.but2).setOnClickListener(new View.OnClickListener() { private WifiUtils instance; @Override public void onClick(View v) { test("ssid-WIFI","密码"); } });}public void verifyStoragePermissions(Activity activity) {ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE, 1);}public void test(String name,String wpd){ if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) { NetworkSpecifier specifier = new WifiNetworkSpecifier.Builder() .setSsidPattern(new PatternMatcher(name, PatternMatcher.PATTERN_PREFIX)) .setWpa2Passphrase(wpd) .build(); NetworkRequest request = new NetworkRequest.Builder() .addTransportType(NetworkCapabilities.TRANSPORT_WIFI) .removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) .setNetworkSpecifier(specifier) .build(); ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); ConnectivityManager.NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback() { @Override public void onAvailable(Network network) { // do success processing here.. } @Override public void onUnavailable() { // do failure processing here.. } }; connectivityManager.requestNetwork(request, networkCallback); // Release the request when done. // connectivityManager.unregisterNetworkCallback(networkCallback); }}
}
完美解决Android9.0以上wifi连接失败的问题~
来源地址:https://blog.csdn.net/hongranzuoxiang/article/details/131183900
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341