当我的手机连接到新的Wifi网络时,我正试图收到通知。
这是我BroadcastReceiver
的逻辑:
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Bundle extras = intent.getExtras();
if (extras != null) {
for (String key : extras.keySet()) {
if(key.equals("networkInfo")){
NetworkInfo info = (NetworkInfo) extras.get(key);
if(info.getType() == ConnectivityManager.TYPE_WIFI){
if(info.getState().toString().equals("CONNECTED")){
//do stuff
}
}
}
}
}
}
}
当我打开Wifi并连接到新网络时,此功能正常。但我的问题是,当我已连接到Wifi网络然后连接到另一个网络时,没有任何反应。
为了实现这一目标,我应该向Actoin
添加哪些IntentFilter
权利?
修改
此代码工作正常。问题是WifiReceiver
未注册。
答案 0 :(得分:2)
请尝试此解决方案,
BroadcastReceiver broadcastReceiver = new WifiBroadcastReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
context.registerReceiver(broadcastReceiver, intentFilter);
您需要检查路由器的MAC地址,以检查Wifi连接是否有变化。
public class WifiBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (WifiManager.SUPPLICANT_STATE_CHANGED_ACTION .equals(action)) {
SupplicantState state = intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE);
if (SupplicantState.isValidState(state)
&& state == SupplicantState.COMPLETED) {
boolean changed = checkWifiChanged();
}
}
}
/** Detect if WiFi is changed. */
private boolean checkWifiChanged() {
boolean changed = false;
// You can store the previous MAC address in Shared Preferences and fetch it here
String previousMacAddress = getPreviousMacAddress();
WifiManager wifiManager =
(WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifi = wifiManager.getConnectionInfo();
if (wifi != null) {
// Get current router MAC address
String bssid = wifi.getBSSID();
changed = !previousMacAddress.equals(bssid);
}
return changed;
}
}
您可以将以前的MAC地址存储在数据库或共享首选项中,并检查新连接的MAC地址与前一个MAC地址。如果它们不同,则WiFi连接已更改,否则不会。