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。
废话不多说直接上代码:
首先需要在清单文件中添加权限:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
其次需要再activity动态申请权限,代码如下:
public class MainActivity extends AppCompatActivity {
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION};
@Override
protected 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);
}
}
}文章来源:https://www.toymoban.com/news/detail-655083.html
完美解决Android9.0以上wifi连接失败的问题~文章来源地址https://www.toymoban.com/news/detail-655083.html
到了这里,关于Android 9.0以上 连接wifi失败 解决方案的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!