如果 WiFi 打开,我正在尝试将布尔值设置为 true。我通过广播接收器的实现来获取连接状态。但是,布尔值不止一次被设置为 true。你能帮我解决这个问题吗?我希望布尔值仅在连接 WiFi 时设置为 true,仅在 WiFi 断开连接时设置为 false。代码如下:
NetworkInfo info = (NetworkInfo) ((ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE))
.getActiveNetworkInfo();
if (info != null) {
Log.d("wifiRun", "Network available");
ConnectivityManager conMan = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo.State wifi = null;
if (conMan.getNetworkInfo(1).isAvailable())
wifi = conMan.getNetworkInfo(1).getState();
if (wifi == NetworkInfo.State.CONNECTED) {
//|| wifi == NetworkInfo.State.CONNECTING) {
wifiState = true;
Log.d("wifiRun", "wifiState: " + wifiState);
} else {
wifiState = false;
Log.d("wifiRun", "wifiState: " + wifiState);
}
}
显现:
<receiver android:name="com.aws.BatteryUsage.ServiceDefinition">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
</intent-filter>
</receiver>