这里,我给出一个函数
1 public boolean sale_connect_check(WifiConfiguration wcg,Context context) { 2 boolean judge_2 = false;//二重判断的布尔变量 3 int wcgID = wifiManager.addNetwork(wcg);//获取所曾网络id 4 boolean judge = wifiManager.enableNetwork(wcgID, true);//就行操作,注意,网上很多连wifi的demo,最后都是用它连的 5 //这里要说明一下,即使返回式true,它也不一定会连上,它只会进行去连wifi的操作 6 try{ 7 Log.d("tag","before sleep here"); 8 Thread.sleep(4000);//线程暂停 4 秒,因为链接wifi是一个过程,我们要给上面的操作时间去做连接 9 ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); 10 NetworkInfo wifiNetworkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); 11 if(wifiNetworkInfo.isConnected()) {//此时,在这里再判断,是否连接上了,如果4秒不够,自己设置 12 Log.d("tag","is do connect"); 13 judge_2 = true ;// 14 } 15 }catch (Exception e){ 16 Log.d("tag",e.toString()); 17 } 18 save_check_sale_judge = judge && judge_2;//2个都是true 19 return save_check_sale_judge;//连接上了 20 }
时间: 2024-10-12 04:49:40