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