Android enables and disables Wi-Fi HotSpot programmatically

Is there an API to enable / disable Wi-Fi HotSpot on Android programmatically?

What methods should be used to turn on / off?

UPDATE: There is an option to enable HotSpot and just turn Wi-Fi on / off, but this is not a good solution for me.

+53
android wifi android wifi
Jun 18 2018-11-11T00:
source share
13 answers

Use the class below to change / check the Wifi hotspot setting:

 import android.content.*; import android.net.wifi.*; import java.lang.reflect.*; public class ApManager { //check whether wifi hotspot on or off public static boolean isApOn(Context context) { WifiManager wifimanager = (WifiManager) context.getSystemService(context.WIFI_SERVICE); try { Method method = wifimanager.getClass().getDeclaredMethod("isWifiApEnabled"); method.setAccessible(true); return (Boolean) method.invoke(wifimanager); } catch (Throwable ignored) {} return false; } // toggle wifi hotspot on or off public static boolean configApState(Context context) { WifiManager wifimanager = (WifiManager) context.getSystemService(context.WIFI_SERVICE); WifiConfiguration wificonfiguration = null; try { // if WiFi is on, turn it off if(isApOn(context)) { wifimanager.setWifiEnabled(false); } Method method = wifimanager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class); method.invoke(wifimanager, wificonfiguration, !isApOn(context)); return true; } catch (Exception e) { e.printStackTrace(); } return false; } } // end of class 

You need to add permissions below for your AndroidMainfest:

 <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" /> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> 

Use this standalone ApManager class from anywhere as follows:

 ApManager.isApOn(YourActivity.this); // check Ap state :boolean ApManager.configApState(YourActivity.this); // change Ap state :boolean 

Hope this helps someone

+52
May 14 '14 at 9:43
source share

There are no Wi-Fi access point features in the Android SDK - sorry!

+8
Jun 18 '11 at 12:13
source share

You can use the following code to automatically enable, disable, and request wifi direct status.

 package com.kusmezer.androidhelper.networking; import java.lang.reflect.Method; import com.google.common.base.Preconditions; import android.content.Context; import android.net.wifi.WifiConfiguration; import android.net.wifi.WifiManager; import android.util.Log; public final class WifiApManager { private static final int WIFI_AP_STATE_FAILED = 4; private final WifiManager mWifiManager; private final String TAG = "Wifi Access Manager"; private Method wifiControlMethod; private Method wifiApConfigurationMethod; private Method wifiApState; public WifiApManager(Context context) throws SecurityException, NoSuchMethodException { context = Preconditions.checkNotNull(context); mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); wifiControlMethod = mWifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class,boolean.class); wifiApConfigurationMethod = mWifiManager.getClass().getMethod("getWifiApConfiguration",null); wifiApState = mWifiManager.getClass().getMethod("getWifiApState"); } public boolean setWifiApState(WifiConfiguration config, boolean enabled) { config = Preconditions.checkNotNull(config); try { if (enabled) { mWifiManager.setWifiEnabled(!enabled); } return (Boolean) wifiControlMethod.invoke(mWifiManager, config, enabled); } catch (Exception e) { Log.e(TAG, "", e); return false; } } public WifiConfiguration getWifiApConfiguration() { try{ return (WifiConfiguration)wifiApConfigurationMethod.invoke(mWifiManager, null); } catch(Exception e) { return null; } } public int getWifiApState() { try { return (Integer)wifiApState.invoke(mWifiManager); } catch (Exception e) { Log.e(TAG, "", e); return WIFI_AP_STATE_FAILED; } } } 
+4
May 13 '13 at 7:12
source share

For Android 8.0, there is a new API for handling hotspots. As far as I know, the old method using reflection no longer works. Please refer to:

Android Developers https://developer.android.com/reference/android/net/wifi/WifiManager.html#startLocalOnlyHotspot(android.net.wifi.WifiManager.LocalOnlyHotspotCallback,%20android.os.Handler)

 void startLocalOnlyHotspot (WifiManager.LocalOnlyHotspotCallback callback, Handler handler) 

Only request a local access point that the application can use to communicate between shared devices connected to the created WiFi access point. The network created by this method will not have access to the Internet.

Stack overflow
How to programmatically turn on / off a Wi-Fi access point in Android 8.0 (Oreo)

The onStarted method (WifiManager.LocalOnlyHotspotReservation) will be called if the hotspot is enabled. Using the WifiManager.LocalOnlyHotspotReservation link, you call the close () method to disable the hotspot.

+3
Jan 25 '18 at 11:29
source share

Itโ€™s best to look at the WifiManager class. In particular, the setWifiEnabled(bool) function.

See documentation at: http://developer.android.com/reference/android/net/wifi/WifiManager.html#setWifiEnabled (boolean)

A tutorial on how to use it (including necessary permissions) can be found here: http://www.tutorialforandroid.com/2009/10/turn-off-turn-on-wifi-in-android-using.html

+2
Jun 18 2018-11-11T00:
source share

Applies only to Oreo + ...

Here I created an application with code on GitHub that uses reflection and DexMaker to โ€œsnapโ€ to the Oreo binding functionality, which is now available in ConnectionManager , and not in WifiManager .

The WifiManager in WifiManager is only good for closed Wi-Fi networks (which explains the Closed bit in class names!).

More explanations of https://stackoverflow.com/a/312618/

+2
Mar 19 '18 at 5:29
source share

This works well for me:

 WifiConfiguration apConfig = null; Method method = wifimanager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, Boolean.TYPE); method.invoke(wifimanager, apConfig, true); 
+1
Feb 18 '14 at 9:02
source share

I am posting an unofficial api for the same, it contains more than just a hotspot turn on/off . link

For the DOC API, a link .

+1
Dec 16 '14 at 8:31
source share

** For Oreo & PIE ** I found a way to get through this

 private WifiManager.LocalOnlyHotspotReservation mReservation; private boolean isHotspotEnabled = false; private final int REQUEST_ENABLE_LOCATION_SYSTEM_SETTINGS = 101; private boolean isLocationPermissionEnable() { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.ACCESS_COARSE_LOCATION}, 2); return false; } return true; } @RequiresApi(api = Build.VERSION_CODES.O) private void turnOnHotspot() { if (!isLocationPermissionEnable()) { return; } WifiManager manager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE); if (manager != null) { // Don't start when it started (existed) 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; isHotspotEnabled = true; } @Override public void onStopped() { super.onStopped(); //Log.d(TAG, "onStopped: "); isHotspotEnabled = false; } @Override public void onFailed(int reason) { super.onFailed(reason); //Log.d(TAG, "onFailed: "); isHotspotEnabled = false; } }, new Handler()); } } @RequiresApi(api = Build.VERSION_CODES.O) private void turnOffHotspot() { if (!isLocationPermissionEnable()) { return; } if (mReservation != null) { mReservation.close(); isHotspotEnabled = false; } } @RequiresApi(api = Build.VERSION_CODES.O) private void toggleHotspot() { if (!isHotspotEnabled) { turnOnHotspot(); } else { turnOffHotspot(); } } @RequiresApi(api = Build.VERSION_CODES.O) private void enableLocationSettings() { LocationRequest mLocationRequest = new LocationRequest(); /*mLocationRequest.setInterval(10); mLocationRequest.setSmallestDisplacement(10); mLocationRequest.setFastestInterval(10); mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);*/ LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder(); builder.addLocationRequest(mLocationRequest) .setAlwaysShow(false); // Show dialog Task<LocationSettingsResponse> task= LocationServices.getSettingsClient(this).checkLocationSettings(builder.build()); task.addOnCompleteListener(task1 -> { try { LocationSettingsResponse response = task1.getResult(ApiException.class); // All location settings are satisfied. The client can initialize location // requests here. toggleHotspot(); } catch (ApiException exception) { switch (exception.getStatusCode()) { case LocationSettingsStatusCodes.RESOLUTION_REQUIRED: // Location settings are not satisfied. But could be fixed by showing the // user a dialog. try { // Cast to a resolvable exception. ResolvableApiException resolvable = (ResolvableApiException) exception; // Show the dialog by calling startResolutionForResult(), // and check the result in onActivityResult(). resolvable.startResolutionForResult(HotspotActivity.this, REQUEST_ENABLE_LOCATION_SYSTEM_SETTINGS); } catch (IntentSender.SendIntentException e) { // Ignore the error. } catch (ClassCastException e) { // Ignore, should be an impossible error. } break; case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE: // Location settings are not satisfied. However, we have no way to fix the // settings so we won't show the dialog. break; } } }); } @RequiresApi(api = Build.VERSION_CODES.O) @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { final LocationSettingsStates states = LocationSettingsStates.fromIntent(data); switch (requestCode) { case REQUEST_ENABLE_LOCATION_SYSTEM_SETTINGS: switch (resultCode) { case Activity.RESULT_OK: // All required changes were successfully made toggleHotspot(); Toast.makeText(HotspotActivity.this,states.isLocationPresent()+"",Toast.LENGTH_SHORT).show(); break; case Activity.RESULT_CANCELED: // The user was asked to change settings, but chose not to Toast.makeText(HotspotActivity.this,"Canceled",Toast.LENGTH_SHORT).show(); break; default: break; } break; } } 

Useage

 btnHotspot.setOnClickListenr(view -> { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // Step 1: Enable the location settings use Google Location Service // Step 2: https://stackoverflow.com/questions/29801368/how-to-show-enable-location-dialog-like-google-maps/50796199#50796199 // Step 3: If OK then check the location permission and enable hotspot // Step 4: https://stackoverflow.com/questions/46843271/how-to-turn-off-wifi-hotspot-programmatically-in-android-8-0-oreo-setwifiapen enableLocationSettings(); return; } } <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> implementation 'com.google.android.gms:play-services-location:15.0.1' 
0
Nov 06 '18 at 6:52
source share

We can programmatically turn on and off

 setWifiApDisable.invoke(connectivityManager, TETHERING_WIFI);//Have to disable to enable setwifiApEnabled.invoke(connectivityManager, TETHERING_WIFI, false, mSystemCallback,null); 

Using the callback class to programmatically enable a hot spot in a pie chart (9.0), you need to programmatically turn off and on.

0
Apr 08 '19 at 9:23
source share

You can use the console and service for this option.

I think you can solve this with this. I did the test right in the console and turned on the hot spot

I found this in this article. Is it possible to connect a USB device via Android via adb via terminal?

And after reading the interface, we can use the same 24, but we need more parameters

service call connection 24 i32 0 i32 1 i32 0 s16 random

0
Jul 11 '19 at 15:17
source share

You can refer to this post to check for new APIs in Android Oreo to enable / disable Wi-Fi hotspot

stack overflow

Below code can be used for this.

 public boolean enableTetheringNew(MyTetheringCallback callback) { File outputDir = mContext.getCodeCacheDir(); try { proxy = ProxyBuilder.forClass(classOnStartTetheringCallback()) .dexCache(outputDir).handler(new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { switch (method.getName()) { case "onTetheringStarted": callback.onTetheringStarted(); break; case "onTetheringFailed": callback.onTetheringFailed(); break; default: ProxyBuilder.callSuper(proxy, method, args); } return null; } }).build(); } catch (IOException e) { e.printStackTrace(); } ConnectivityManager manager = (ConnectivityManager) mContext.getApplicationContext().getSystemService(ConnectivityManager.class); Method method = null; try { method = manager.getClass().getDeclaredMethod("startTethering", int.class, boolean.class, classOnStartTetheringCallback(), Handler.class); if (method == null) { Log.e(TAG, "startTetheringMethod is null"); } else { method.invoke(manager, TETHERING_WIFI, false, proxy, null); } return true; } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } return false; } private Class classOnStartTetheringCallback() { try { return Class.forName("android.net.ConnectivityManager$OnStartTetheringCallback"); } catch (ClassNotFoundException e) { e.printStackTrace(); } return null; 

}

-2
Sep 10 '18 at 5:23
source share
 WifiManager wifiManager = (WifiManager)this.context.getSystemService(Context.WIFI_SERVICE); wifiManager.setWifiEnabled(status); 

where the status can be true or false

add permission manifest: <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />

-3
Aug 17 '12 at 15:55
source share



All Articles