Android9开始,WIFI那块的api发生了改变: addNetwork(WifiConfiguration config) 此方法在API级别Q中已弃用) 见addNetworkSuggestions(java.util.List),
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
--结束END--
本文标题: Android 9.0以上 连接wifi失败 解决方案
本文链接: https://lsjlt.com/news/374602.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0