How to turn on/off wifi hotspot programmatically in Android 8.0 (Oreo)

前端 未结 3 2140
梦毁少年i
梦毁少年i 2020-11-27 05:38

I know how to turn on/off wifi hot spot using reflection in android using below method.

private static boolean changeWifiHotspotState(Context context,boolean         


        
3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-27 06:41

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

    Below is the code to turn on hotspot

    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) method will be called if hotspot is turned on.. Using WifiManager.LocalOnlyHotspotReservation reference you call close() method to turn off hotspot.

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

提交回复
热议问题