且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Android 8.0 (Oreo) 中以编程方式打开/关闭 wifi 热点

更新时间:2023-01-02 10:15:57

我终于找到了解决方案.Android 8.0,他们提供了公共api来打开/关闭热点.WifiManager

Finally I got the solution. Android 8.0, they provided public api to turn on/off hotspot. WifiManager

以下是开启热点的代码

private WifiManager.LocalOnlyHotspotReservation mReservation;

@RequiresApi(api = Build.VERSION_CODES.O)
private void turnOnHotspot() {
    WifiManager manager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);

    manager.startLocalOnlyHotspot(new WifiManager.LocalOnlyHotspotCallback() {

        @Override
        public void onStarted(WifiManager.LocalOnlyHotspotReservation reservation) {
            super.onStarted(reservation);
            Log.d(TAG, "Wifi Hotspot is on now");
            mReservation = reservation;
        }

        @Override
        public void onStopped() {
            super.onStopped();
            Log.d(TAG, "onStopped: ");
        }

        @Override
        public void onFailed(int reason) {
            super.onFailed(reason);
            Log.d(TAG, "onFailed: ");
        }
    }, new Handler());
}

private void turnOffHotspot() {
    if (mReservation != null) {
        mReservation.close();
    }
}

onStarted(WifiManager.LocalOnlyHotspotReservation reserved) 方法将在热点打开时调用.. 使用 WifiManager.LocalOnlyHotspotReservation 引用您调用 close()代码>方法来关闭热点.

onStarted(WifiManager.LocalOnlyHotspotReservation reservation) method will be called if hotspot is turned on.. Using WifiManager.LocalOnlyHotspotReservation reference you call close() method to turn off hotspot.

注意:要打开热点,应在设备中启用 Location(GPS).否则会抛出SecurityException

Note: To turn on hotspot, the Location(GPS) should be enabled in the device. Otherwise, it will throw SecurityException