很多人已经问过这个问题,但是对他们有用的解决方案对我不起作用。我在 Android 8.1 和 Android 9.0 上测试过,无法获取 SSID 的名称。
用于获取 WiFi 状态变化的广播接收器:
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION) ||
intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION) ||
intent.getAction().equals(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION) ||
intent.getAction().equals(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION) ||
intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
setWifiIndicator();
}
}
};
接收器在 中注册onCreate和注销onDestroy,我认为这是正确的,并且在调用接收器时我看到了日志行。
在onCreate:
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ScannerService.ACTION_READ_SCANNER);
intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
intentFilter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
intentFilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
registerReceiver(mReceiver, intentFilter);
setWifiIndicator();
setWifiIndicator是这样实现的:
private void setWifiIndicator() {
ConnectivityManager connMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
//getApplicationContext solves memory leak issues prior to Android N (must use Application Context to get wifi system service.
WifiManager wifiMgr = (WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE);
ImageView wifiIndicator = (ImageView)findViewById(R.id.wifi_indicator);
TextView wifiSSID = (TextView)findViewById(R.id.wifi_ssid);
阿晨1998
MYYA
相关分类