且构网

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

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

更新时间:2023-01-02 11:12:07

最后,我得到了解决方案. Android 8.0,他们提供了公共api来打开/关闭热点.

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 reservation)方法.使用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