2

I use this code to activate or deactivate the tethering hotspot so other devices can use the Internet data of my device. It used to work well but it is not working anymore for Nougat, do you have any hint? thanks.

This is the code I use:

  private boolean ActivateTethering(boolean bEstate) 
  {  WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);

     Method[] methods = wifiManager.getClass().getDeclaredMethods();
     for(Method method : methods) 
     {  if(method.getName().equals("setWifiApEnabled")) 
        {  try 
           {  if(bEstate == true)
              {  wifiManager.setWifiEnabled(false); //Turning off wifi because tethering requires wifi to be off
                 method.invoke(wifiManager, null, true); //Activating tethering
                 return true;
              }
              else
              {  method.invoke(wifiManager, null, false); //Deactivating tethering
                 return true;
              }
           }
           catch(Exception e) 
           {  return false;
           }           
         }
     }

     //Error setWifiApEnabled not found 
     return false;
 }

I get the error java.lang.reflect.InvocationTargetException

Floern
  • 33,559
  • 24
  • 104
  • 119
Ton
  • 9,235
  • 15
  • 59
  • 103

1 Answers1

0

Use this instead

try {
    Method method = wifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
    method.invoke(wifiManager, null, true); // true to enable, false to disable
} catch (NoSuchMethodException e) {
    // WiFi tethering is blocked.
}

Change it for your needs It works on my S7 Edge while getDeclaredMethods(); way does not.

Rambalac
  • 2,592
  • 2
  • 15
  • 14