Wi-Fiの変更を検出できません。アプリでWi-Fiネットワークを監視し、Wi-Fiが切断された場合にアラートダイアログを作成したいのですが。起動時、再開時など、またはb。接続が失われたときはいつでも。これが私のコードです(これをonResumeにthis.registerReceiver(wifiStatusReceiver、new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION))で登録し、onPauseで登録を解除します):
BroadcastReceiver wifiStatusReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
int extraWifiState = intent.getIntExtra(
WifiManager.EXTRA_WIFI_STATE,
WifiManager.WIFI_STATE_UNKNOWN);
final String action = intent.getAction();
DialogFragment dialog = (DialogFragment) fragmentManager
.findFragmentByTag(WifiAlertDialogFragment.DIALOG_WIFI);
if (action.equals(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION)) {
NetworkInfo info = (NetworkInfo) intent
.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
if (info.getState().equals(NetworkInfo.State.CONNECTED)) {
logger.d("wifi changed, is still connected");
if (dialog != null)
dialog.dismiss();
} else {
logger.d("connection lost");
if (dialog == null)
WifiAlertDialogFragment.wifiCheck(HomeActivity.this);
}
}
switch (extraWifiState) {
case WifiManager.WIFI_STATE_DISABLED:
WifiAlertDialogFragment.wifiCheck(HomeActivity.this);
break;
case WifiManager.WIFI_STATE_DISABLING:
Toast.makeText(HomeActivity.this, R.string.wifi_disabled,
Toast.LENGTH_SHORT).show();
WifiAlertDialogFragment.wifiCheck(HomeActivity.this);
break;
case WifiManager.WIFI_STATE_ENABLED:
if (dialog != null)
dialog.dismiss();
break;
case WifiManager.WIFI_STATE_ENABLING:
if (dialog != null)
dialog.dismiss();
Toast.makeText(HomeActivity.this, "Wifi Enabling",
Toast.LENGTH_LONG).show();
break;
case WifiManager.WIFI_STATE_UNKNOWN:
// no op
break;
}
}
};