0

I tried many codes,so no solution found to change the wifi hotspot status.can anyone give me the sample code to just turn wifi hotspot on and off?

Semo
  • 1
  • 3

1 Answers1

1

For API<26, there is no public API in the Android SDK. But you can use reflection if you want.

 public boolean setWifiEnabled(WifiConfiguration wifiConfig, boolean enabled) { 
 WifiManager wifiManager;
try {   
  if (enabled) { //disables wifi hotspot if it's already enabled    
    wifiManager.setWifiEnabled(false);  
  } 

   Method method = wifiManager.getClass()   
      .getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);   
  return (Boolean) method.invoke(wifiManager, wifiConfig, enabled); 
} catch (Exception e) { 
  Log.e(this.getClass().toString(), "", e); 
  return false; 
}   
}

But you would need WRITE_SYSTEM_SETTINGS permission. Declare it in manifest.xml

  <uses-permission  
      android:name="android.permission.WRITE_SETTINGS"  
      tools:ignore="ProtectedPermissions"/>

Ask the permission on run-time.

 private boolean showWritePermissionSettings() {    
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M  
    && Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { 
  if (!Settings.System.canWrite(this)) {    
    Log.v("DANG", " " + !Settings.System.canWrite(this));   
    Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_WRITE_SETTINGS); 
    intent.setData(Uri.parse("package:" + this.getPackageName()));  
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
    this.startActivity(intent); 
    return false;   
  } 
}   
return true; //Permission already given 
}

For API>=26, you can implement this solution.

Adeel Zafar
  • 361
  • 2
  • 16