Androidで無線LANの状態の取得と設定は簡単に行える。
まず、manifestにおまじないを記述しておく。
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
取得のみであれば、CHANGE_WIFI_STATEは不要だ。コードは単純で、
WifiManager wifi; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); wifi = (WifiManager)getSystemService(WIFI_SERVICE); } public boolean checkWifi() { return (wifi.isWifiEnabled()); } public void setWifi(boolean set){ wifi.setWifiEnabled(set); }
WiFiの状態は変化するので、状態に変化があれば取得したい場合、BroadcastReceiverを登録しておく。
@Override protected void onResume() { super.onResume(); IntentFilter filter = new IntentFilter(); filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION); registerReceiver(mBroadcastReceiver, filter); } @Override protected void onPause() { super.onPause(); unregisterReceiver(mBroadcastReceiver); } private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) { int extraWifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE , WifiManager.WIFI_STATE_UNKNOWN); if (extraWifiState == WifiManager.WIFI_STATE_DISABLED){ } else if (extraWifiState == WifiManager.WIFI_STATE_ENABLED){ } } } };
This post is also available in: 英語