当我试图返回wifi状态,断开连接或连接时,我遇到了问题。好吧,我没有得到异常,但它跳转到我的if条件的else {}块,当我调试时,我发现:< / p>
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
mWifi有这个:NetworkInfo:类型:wifi [],状态:UNKNOWN / IDLE,原因:(未指定)
ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (mWifi.isConnectedOrConnecting()){
Toast.makeText(this,"void action Working", 3).show();
}
else
{
Toast.makeText(this,"void action Not working", 3).show();
}
答案 0 :(得分:1)
你可以这样做:
final WifiManager wifiManager = (WifiManager) YourActivity.this.getSystemService(Context.WIFI_SERVICE);
if (!wifiManager.isWifiEnabled()) {
wifiManager.setWifiEnabled(true); //If it's, off turn it on.
}else{
//Do what you want to do with wi-fi.
}
另请注意,我在清单中设置了以下权限(在您实现wifi直接功能时,可能并非所有这些都是必需的):
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission
android:name="android.permission.ACCESS_WIFI_STATE"
android:required="true" />
<uses-permission
android:name="android.permission.CHANGE_WIFI_STATE"
android:required="true" />
<uses-permission
android:name="android.permission.INTERNET"
android:required="true" />