我試圖設置一個布爾值爲true,如果WiFi處於打開狀態。我通過實現廣播接收器來獲取連接狀態。但是,布爾值不止一次被設置爲true。你能幫我解決這個問題嗎?我只想在連接WiFi時將布爾值設置爲true,並且僅在WiFi斷開連接時設置爲false。代碼如下:WiFi狀態更改
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>
好主意。我是否應該在清單文件中提供任何權限? – madhu
哦,是的 - 你說得對。我編輯帖子(添加所需的權限) –
@JacekMilewski:我正在實施這項技術。非常感謝你。最後,我是否應該在清單中爲此註冊supplicant.CONNECTION_CHANGE_ACTION? – madhu