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

匿名 (未验证) 提交于 2019-12-03 01:27:01

问题:

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

private static boolean changeWifiHotspotState(Context context,boolean enable) {         try {             WifiManager manager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);             Method method = manager.getClass().getDeclaredMethod("setWifiApEnabled", WifiConfiguration.class,                     Boolean.TYPE);             method.setAccessible(true);             WifiConfiguration configuration = enable ? getWifiApConfiguration(manager) : null;             boolean isSuccess = (Boolean) method.invoke(manager, configuration, enable);             return isSuccess;         } catch (Exception e) {             e.printStackTrace();         }         return false;     } 

But the above method is not working Android 8.0(Oreo).

When I execute above method in Android 8.0, I am getting below statement in logcat.

com.gck.dummy W/WifiManager: com.gck.dummy attempted call to setWifiApEnabled: enabled = true 

Is there any other way to on/off hotspot on android 8.0

回答1:

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

@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");             }              @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());     } 

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.

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



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