简体   繁体   English

WiFi getSSID() 总是返回“<unknown ssid> ”

[英]WiFi getSSID() always returns "<unknown ssid>"

This question has already been asked by many people, but the solution that worked for them is not working for me.很多人已经问过这个问题,但是对他们有用的解决方案对我不起作用。 I have tested on Android 8.1 and Android 9.0 and cannot get the name of the SSID.我已经在 Android 8.1 和 Android 9.0 上进行了测试,但无法获取 SSID 的名称。

Broadcast receiver for getting WiFi state changes:用于获取 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();
        }
    }
};

The receiver is registered onCreate and unregistered in onDestroy , which I think is proper, and I'm seeing the log lines when the receiver is called.接收器在onCreate中注册并在onDestroy取消注册,我认为这是正确的,并且当接收器被调用时我看到了日志行。

in onCreate :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 is implemented thusly: 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();
    }
}

My app already had permission for ACCESS_COARSE_LOCATION but I aslo added ACCESS_FINE_LOCATION just in case.我的应用程序已经获得了ACCESS_COARSE_LOCATION许可,但我也添加了ACCESS_FINE_LOCATION以防万一。 getSSID() is till returning <unknown ssid> . 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" />

Perhaps it has to do with compile target SDK?也许它与编译目标SDK有关? I'm really clueless here.我在这里真的一窍不通。

gradle file:毕业文件:

apply plugin: 'com.android.application'应用插件:'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')
}

Wi-Fi Permissions Wi-Fi 权限

Android 8.0 and Android 8.1:安卓 8.0 和安卓 8.1:

A successful call to WifiManager.getScanResults() requires any one of the following permissions:成功调用 WifiManager.getScanResults() 需要以下任一权限:

• ACCESS_FINE_LOCATION • ACCESS_COARSE_LOCATION • CHANGE_WIFI_STATE • ACCESS_FINE_LOCATION • ACCESS_COARSE_LOCATION • CHANGE_WIFI_STATE

If the calling app does not have any of these permissions, the call fails with a SecurityException.如果调用应用程序没有这些权限中的任何一个,调用将失败并出现 SecurityException。

Android 9:安卓 9:

A successful call to WifiManager.startScan() requires all of the following conditions to be met:成功调用 WifiManager.startScan() 需要满足以下所有条件:

• Your app has the ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION permission. • 您的应用程序具有 ACCESS_FINE_LOCATION 或 ACCESS_COARSE_LOCATION 权限。 • Your app has the CHANGE_WIFI_STATE permission. • 您的应用程序具有 CHANGE_WIFI_STATE 权限。 • Location services are enabled on the device (under Settings > Location). • 在设备上启用了定位服务(在设置 > 定位下)。

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

A successful call to WifiManager.startScan() requires all of the following conditions to be met:成功调用 WifiManager.startScan() 需要满足以下所有条件:

• If your app is targeting Android 10 (API level 29) SDK or higher, your app has the ACCESS_FINE_LOCATION permission. • 如果您的应用面向 Android 10(API 级别 29)SDK 或更高版本,则您的应用具有 ACCESS_FINE_LOCATION 权限。

• If your app is targeting SDK lower than Android 10 (API level 29), your app has the ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission. • 如果您的应用面向低于 Android 10(API 级别 29)的 SDK,则您的应用具有 ACCESS_COARSE_LOCATION 或 ACCESS_FINE_LOCATION 权限。

• Your app has the CHANGE_WIFI_STATE permission. • 您的应用程序具有 CHANGE_WIFI_STATE 权限。

• Location services are enabled on the device (under Settings > Location). • 在设备上启用了定位服务(在设置 > 定位下)。

And Request User level permission to achieve并请求用户级别权限实现

See this link for more information: https://developer.android.com/guide/topics/connectivity/wifi-scan#wifi-scan-permissions有关更多信息,请参阅此链接: https : //developer.android.com/guide/topics/connectivity/wifi-scan#wifi-scan-permissions

XAMARIN FORMS Code Change: XAMARIN 表单代码更改:

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];
}
}

在此处输入图片说明

Have you tried to check if getSupplicantState() is COMPLETED ?您是否尝试过检查getSupplicantState()COMPLETED

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

Also, have you asked for this before running the BroadcastReceiver or even inside you can do it :另外,您是否在运行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(); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM