2017-04-08 110 views

回答

0

您可以使用下面的獨立的類:

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; 
    } 
} 

現在,一旦你已經創建的類以下權限將被添加到您的清單:

<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" /> 
<uses-permission android:name="android.permission.WRITE_SETTINGS" /> 

做以上後,以下代碼切換熱點:

ApManager.configApState(MainActivity.this);

您需要通過準確的上下文來代替MainActivity.this

我很久以前就使用過這個類,並沒有完全記得我從它那裏得到的源代碼。

+0

仍然不起作用。什麼都沒發生。 wifi只是關掉,就是這樣。 – NobleSiks

+0

你目前使用哪個android版本?我在Android 6.0.1上,MIUI8。 –