2015-07-11 73 views
0

爲什麼這段代碼在android 5.0中不起作用?如何在Android 5.0中使用WiFi熱點

我應該打電話來打開/關閉Android中的哪些方法5.0

WifiConfiguration wificonfiguration = new WifiConfiguration(); 
 
wificonfiguration.SSID = "Wifi Hotspot"; 
 

 
wificonfiguration.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN); 
 
wificonfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK); 
 
wificonfiguration.preSharedKey = "123"; 
 
WifiManager mWifiManager; 
 
mWifiManager = (WifiManager) this.context1.getSystemService(Context.WIFI_SERVICE); 
 

 

 
try { 
 
    if (mWifiManager.isWifiEnabled()) { // disable WiFi in any case 
 
    mWifiManager.setWifiEnabled(false); 
 
    } 
 

 
    Method method = mWifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class); 
 

 
    method.invoke(mWifiManager, wificonfiguration, true); 
 

 

 

 

 
    //Toast.makeText(context, "OK", 0).show(); 
 

 
} catch (Exception e) { 
 
    Log.e(this.getClass().toString(), "", e); 
 
}

添加在清單:

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

logs?有什麼異常? –

+0

在WPA的旁註中,密碼必須至少包含8個字符 – unrealsoul007

回答

0

你應該抓住特定的例外知道錯在哪裏更清晰。 試試這個 -

private boolean setWifiApEnabled() 
    { 
     boolean result = false; 
     // initialise you wifiManager first 
     wifiManager.setWifiEnabled(false); 
     Method enableWifi; 
     try { 
      enableWifi = wifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class); 
     } catch (NoSuchMethodException e) { 
      Logger.e(TAG,e.toString()); 
      return result; 
     } 

     WifiConfiguration myConfig = new WifiConfiguration(); 
     myConfig.SSID = "Your SSID"; 
     myConfig.preSharedKey = "Your pass"; 
     myConfig.status = WifiConfiguration.Status.ENABLED; 
     myConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK); 
     myConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN); 
     myConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA); 
     myConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP); 
     myConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP); 
     myConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP); 
     myConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP); 
     try { 
      result = (Boolean) enableWifi.invoke(wifiManager, myConfig,status); 
     } catch (IllegalAccessException | IllegalArgumentException 
       | InvocationTargetException e) { 
      Logger.e(TAG,e.toString()); 
      return result; 
     } 

     return result; 
    } 
+0

感謝幫助,但無法正常工作。 – Jakvar

+0

您是否嘗試過多種設備? –

+0

我正在嘗試我發佈的相同的代碼,它的工作原理 –