2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Android の Wi-Fi 関連の実装についての話

Last updated at Posted at 2022-03-26

はじめに

今更ながら Android で Wi-Fi まわりの実装を行う機会があったので個人的にまとめました。
いくつかのメソッドは This method was deprecated in API level 29. なので注意が必要です。

Android Developers Reference

パーミッション

AndroidManifest.xml に以下を追加します。

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />

Wi-Fi が有効かどうか取得する

Wi-Fi が有効か無効かを取得します。

// Java
WifiManager manager = (WifiManager) getSystemService(WIFI_SERVICE);
boolean enabled = manager.isWifiEnabled();
// Kotlin
val manager = applicationContext.getSystemService(WIFI_SERVICE) as WifiManager
val enabled = manager.isWifiEnabled

Wi-Fi の情報を取得する

  • SSID
// Java
WifiManager manager = (WifiManager) getSystemService(WIFI_SERVICE);
WifiInfo info = manager.getConnectionInfo();
String ssid = info.getSSID();

Wi-Fi に接続する

登録済みの Wi-Fi に接続します。

// Java
WifiManager manager = (WifiManager) getSystemService(WIFI_SERVICE);
WifiConfiguration config = null;
for (WifiConfiguration network : manager.getConfiguredNetworks()) {
    if (network.SSID.equals('"' + `ssid` + '"')) {
        config = network;
        break;
    }
}
if (config != null) {
    wm.enableNetwork(config.networkId, true);
}

Wi-Fi を切断する

Wi-Fi を無効にします。

// Java
WifiManager manager = (WifiManager) getSystemService(WIFI_SERVICE);
WifiInfo info = manager.getConnectionInfo();
manager.disableNetwork(info.getNetworkId());
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?