清单:
<receiver android:name=".triggers.WifiTrigger">
<intent-filter>
<action android:name="android.net.wifi.STATE_CHANGE" />
</intent-filter>
</receiver>
Permissions:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
当WiFi被禁用,连接或断开(未检查连接/禁用/启用)时执行接收器但是启用WiFi时不会触发接收器,此外WifiManager.EXTRA_WIFI_STATE
额外不可用意图,我正在使用这个:
public class WifiTrigger extends BroadcastReceiver {
...
@Override
public void onReceive(Context context, Intent intent) {
SharedPreferences preferences= PreferenceManager.getDefaultSharedPreferences(context);
int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_UNKNOWN);
int previousWifiState = intent.getIntExtra(WifiManager.EXTRA_PREVIOUS_WIFI_STATE, WifiManager.WIFI_STATE_UNKNOWN);
log("p"+previousWifiState);
log("c"+wifiState);
//log is a defined method used for logging (it just calls Log.d(...,...)
}
...
}
并且不断记录p4
c4
(4代表WifiManager.WIFI_STATE_UNKNOWN)
答案 0 :(得分:5)
您正在注册错误的Intent操作。你真正想要的是:
/** * Broadcast intent action indicating that Wi-Fi has been enabled, disabled, * enabling, disabling, or unknown. One extra provides this state as an int. * Another extra provides the previous state, if available. * * @see #EXTRA_WIFI_STATE * @see #EXTRA_PREVIOUS_WIFI_STATE */ @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) public static final String WIFI_STATE_CHANGED_ACTION = "android.net.wifi.WIFI_STATE_CHANGED";
您注册的操作是针对网络状态更改,而不是适配器状态更改:
/** * Broadcast intent action indicating that the state of Wi-Fi connectivity * has changed. One extra provides the new state * in the form of a {@link android.net.NetworkInfo} object. If the new * state is CONNECTED, additional extras may provide the BSSID and WifiInfo of * the access point. * as a {@code String}. * @see #EXTRA_NETWORK_INFO * @see #EXTRA_BSSID * @see #EXTRA_WIFI_INFO */ @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) public static final String NETWORK_STATE_CHANGED_ACTION = "android.net.wifi.STATE_CHANGE";
只需更改您的接收者注册:
<receiver android:name=".triggers.WifiTrigger">
<intent-filter>
<action android:name="android.net.wifi.STATE_CHANGE" />
</intent-filter>
</receiver>
到
<receiver android:name=".triggers.WifiTrigger">
<intent-filter>
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
</intent-filter>
</receiver>
将解决您的问题。