WiFi getSSID()始终返回“ <unknown ssid =”“>”

时间:2019-02-17 19:28:22

标签: java android wifi

许多人已经问过这个问题,但是对他们有用的解决方案对我却不起作用。我已经在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);

    try {
        if (wifiMgr != null) {
            if (wifiMgr.isWifiEnabled()) {
                //wifi is enabled.  toggle on wifi indicator.
                wifiIndicator.setImageResource(R.drawable.wifi_indicator);
                String ssid = wifiMgr.getConnectionInfo().getSSID();
                if (ssid != null) {
                    Log.v(this.getClass().getSimpleName(), "SSID: " + ssid + "  Supplicant State: " + info.getSupplicantState());
                    wifiSSID.setText(ssid);
                }
            } else {
                //wifi is disabled.  toggle off wifi indicator.
                wifiSSID.setText("");

                //check for 3G
                NetworkInfo mobileInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
                if (mobileInfo != null && mobileInfo.getState().equals(NetworkInfo.State.CONNECTED)) {
                    wifiIndicator.setImageResource(R.drawable.cellular_indicator);
                } else {
                    wifiIndicator.setImageResource(R.drawable.down_indicator);
                }
            }
        } else {
            //check for 3G
            NetworkInfo mobileInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            if (mobileInfo != null && mobileInfo.getState().equals(NetworkInfo.State.CONNECTED)) {
                wifiIndicator.setImageResource(R.drawable.cellular_indicator);
            } else {
                wifiIndicator.setImageResource(R.drawable.down_indicator);
            }
        }
    } catch(Exception e) {
        //catching anything thrown in this block just so it doesn't crash the program unnecessarily
        e.printStackTrace();
    }
}

我的应用已获得ACCESS_COARSE_LOCATION的许可,但我还添加了ACCESS_FINE_LOCATION,以防万一。 getSSID()直到返回<unknown ssid>

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.GET_TASKS" />

也许与编译目标SDK有关?我真的很笨。

渐变文件:

应用插件:“ com.android.application”

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.noneofyour.business"
        minSdkVersion 15
        targetSdkVersion 28
        versionCode 59
        versionName "1.44"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:28.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation files('libs/android.jar')
}

2 个答案:

答案 0 :(得分:1)

您是否尝试检查getSupplicantState()是否为COMPLETED

if(wifiInfo.getSupplicantState() == SupplicantState.COMPLETED){
        String ssid = wifiInfo.getSSID();
        wifiSSID.setText(ssid);
}

此外,您是否在运行BroadcastReceiver之前甚至在内部就可以做到这一点?

 if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION);
}else{setWifiIndicator(); 

答案 1 :(得分:0)

Wi-Fi权限

Android 8.0和Android 8.1:

成功调用WifiManager.getScanResults()需要以下任一权限:

•ACCESS_FINE_LOCATION •ACCESS_COARSE_LOCATION •CHANGE_WIFI_STATE

如果正在调用的应用没有这些权限,则调用将失败,并显示SecurityException。

Android 9:

对WifiManager.startScan()的成功调用需要满足以下所有条件:

•您的应用程序具有ACCESS_FINE_LOCATION或ACCESS_COARSE_LOCATION权限。 •您的应用拥有CHANGE_WIFI_STATE权限。 •在设备上启用了位置服务(在“设置”>“位置”下)。

Android 10(API级别29)及更高版本:

对WifiManager.startScan()的成功调用需要满足以下所有条件:

•如果您的应用程序针对的是Android 10(API级别29)SDK或更高版本,则您的应用程序具有ACCESS_FINE_LOCATION权限。

•如果您的应用程序的目标SDK低于Android 10(API级别29),则您的应用程序具有ACCESS_COARSE_LOCATION或ACCESS_FINE_LOCATION权限。

•您的应用拥有CHANGE_WIFI_STATE权限。

•在设备上启用了位置服务(在“设置”>“位置”下)。

并请求用户级别权限来实现

有关更多信息,请参见此链接:https://developer.android.com/guide/topics/connectivity/wifi-scan#wifi-scan-permissions

XAMARIN FORMS代码更改:

if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.O){
status = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Location);
if (status != PermissionStatus.Granted)
{   
var results = await CrossPermissions.Current.RequestPermissionsAsync(new[] { Permission.Location });
status = results[Permission.Location];
}
}

enter image description here