How do I get the current state of LocalOnlyHotspot?

你说的曾经没有我的故事 提交于 2021-01-29 14:01:08

问题


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:


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


来源:https://stackoverflow.com/questions/53149330/how-do-i-get-the-current-state-of-localonlyhotspot

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!