Android取得目前wifi連線資料

API 31(含)以後,寫法變了,

https://developer.android.com/reference/kotlin/android/net/wifi/WifiManager#getConnectionInfo()
照著官方這樣寫,似乎還是無法取得連線資料,須加上 FLAG_INCLUDE_LOCATION_INFO 才行。

WifiManager wifiManager = (WifiManager) activity.getApplicationContext().getSystemService(Context.WIFI_SERVICE);

final NetworkRequest request = new NetworkRequest.Builder()
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI).build();
ConnectivityManager connectivityManager = activity.getSystemService(ConnectivityManager.class);

ConnectivityManager.NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback(FLAG_INCLUDE_LOCATION_INFO) {
@Override
public void onAvailable(Network network) {}

@Override
public void onCapabilitiesChanged(Network network, NetworkCapabilities networkCapabilities) {
WifiInfo wifiInfo = (WifiInfo) networkCapabilities.getTransportInfo();
String aConnectedWifiSSD = wifiInfo.getSSID().toLowerCase();
Log.d(TAG,"wifiInfo="+wifiInfo);
connectivityManager.unregisterNetworkCallback( this);

}
};
if( wifiManager.isWifiEnabled() ) {
connectivityManager.requestNetwork(request, networkCallback); // For request
connectivityManager.registerNetworkCallback(request, networkCallback); // For listen
}
# 需要的權限
android.Manifest.permission#ACCESS_FINE_LOCATION
android.Manifest.permission#ACCESS_WIFI_STATE

發表迴響