How do I get the current state of LocalOnlyHotspot?

853 Views Asked by At

Android O offers wifiManager.startLocalOnlyHotspot to create a closed network. For designing a shortcut or widge to toggle this kind of hotspot, how could I know the status of LocalOnlyHotspot to judge to start or close it?

And when I start a localOnlyHotspot, how can other device connect to it? (how to get the password of it?)

1

There are 1 best solutions below

1
On

This code may help you to get it running. I implemented a Hotspotmanager Class, which can be used in applications. After turning on the hotspot, it deliveres a wificonfiguration object to a listener which you have to implement in your calling activity. From this config, you can take the SSID and preSharedKey. NOTE: SSID and Password can't be changed!!! Because the creation is fully hidden in Androids system API.

public class HotspotManager {
private final WifiManager wifiManager;
private final OnHotspotEnabledListener onHotspotEnabledListener;
private WifiManager.LocalOnlyHotspotReservation mReservation;

public interface OnHotspotEnabledListener{
    void OnHotspotEnabled(boolean enabled, @Nullable WifiConfiguration wifiConfiguration);
}

//call with Hotspotmanager(getApplicationContext().getSystemService(Context.WIFI_SERVICE),this) in an activity that implements the Hotspotmanager.OnHotspotEnabledListener
public HotspotManager(WifiManager wifiManager, OnHotspotEnabledListener onHotspotEnabledListener) {
    this.wifiManager = wifiManager;
    this.onHotspotEnabledListener = onHotspotEnabledListener;
}

@RequiresApi(api = Build.VERSION_CODES.O)
public void turnOnHotspot() {
    wifiManager.startLocalOnlyHotspot(new WifiManager.LocalOnlyHotspotCallback() {

        @Override
        public void onStarted(WifiManager.LocalOnlyHotspotReservation reservation) {
            super.onStarted(reservation);
            mReservation = reservation;
            onHotspotEnabledListener.OnHotspotEnabled(true, mReservation.getWifiConfiguration());
        }

        @Override
        public void onStopped() {
            super.onStopped();
        }

        @Override
        public void onFailed(int reason) {
            super.onFailed(reason);
        }
    }, new Handler());
}

@RequiresApi(api = Build.VERSION_CODES.O)
public void turnOffHotspot() {
    if (mReservation != null) {
        mReservation.close();
        onHotspotEnabledListener.OnHotspotEnabled(false, null);
    }
}