Frederick Zhang
Frederick Zhang

Reputation: 3683

Android Wear WifiManager - Have to Manually Open WiFi in Settings to Get Results

I'm trying to get currently available WiFi list in a Moto 360 Sport (Android 6.0.1). My code works but I have to manually open WiFi in Settings so that the BroadcastReceiver can be called.

My WiFi receiver:

broadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
            List<ScanResult> scanResults = wifiManager.getScanResults();
            sendWifiResult(scanResults);
            unregister();
        }
    }
};

I have requested a bunch of permissions from the user:

private static String[] permissions = {
        "android.permission.BODY_SENSORS",
        "android.permission.RECORD_AUDIO",
        "android.permission.INTERNET",
        "android.permission.ACCESS_NETWORK_STATE",
        "android.permission.CHANGE_WIFI_STATE",
        "android.permission.ACCESS_WIFI_STATE",
        "android.permission.LOCATION_HARDWARE",
        "android.permission.ACCESS_FINE_LOCATION",
        "android.permission.ACCESS_COARSE_LOCATION",
        "android.permission.ACCESS_LOCATION_EXTRA_COMMANDS",
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // some unrelated codes

    if (!checkPermissions())
        this.requestPermissions(permissions, 1);
    else
        startService(new Intent(this, DataSourceService.class));
}

private boolean checkPermissions() {
    for (String permission : permissions) {
        if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED)
            return false;
    }
    return true;
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (checkSelfPermission("android.permission.BODY_SENSORS")
            != PackageManager.PERMISSION_GRANTED)
        requestPermissions(permissions, 1);
    else
        startService(new Intent(this, DataSourceService.class));
}

I have searched a lot. But all the related issues I found were either all or nothing - they worked everything out, or, they couldn't get the broadcast or got empty lists.

In my case, I did get the results, but only if I open the WiFi in System Settings on my own.

This is really weird and I wasn't able to find a solution. Do I need any special configurations in Android Wears?

Any help would be appreciated. Thanks.

Upvotes: 0

Views: 337

Answers (1)

Frederick Zhang
Frederick Zhang

Reputation: 3683

Resolved. So rather than using

if (!wifiManager.isWifiEnabled()) {
    wifiManager.setWifiEnabled(true);
}

...simply fire

wifiManager.setWifiEnabled(true);

directly. For some reason the isWifiEnabled() always returns true.

Upvotes: 1

Related Questions