首页  编辑  

安卓Android 5.0开启wifi热点

Tags: /Android/   Date Created:
android 没有提供标准的api供我们使用,所以只能采取反射机制,去调用hide掉的接口。
使用wifi 首先要在manifest 文件中添加一下权限。
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
创建wifi热点需要先将wifi关闭,然后配置wifiapconfig,通过发射机制开启wifiap。主代码如下。
public WifiManager mWifiManager;
mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);

createWiFiAP(createWifiConfig("jason_test","123456"), true);

public WifiConfiguration createWifiConfig(String ssid, String password) {
   WifiConfiguration apConfig = new WifiConfiguration();
   apConfig.allowedAuthAlgorithms.clear();
   apConfig.allowedGroupCiphers.clear();
   apConfig.allowedKeyManagement.clear();
   apConfig.allowedPairwiseCiphers.clear();
   apConfig.allowedProtocols.clear();
   apConfig.SSID = ssid;
   apConfig.hiddenSSID = true;
   apConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
   apConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
   apConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
   apConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
   apConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
   apConfig.status = WifiConfiguration.Status.ENABLED;
   apConfig.preSharedKey = password;
   return apConfig;
}

public void createWiFiAP(WifiConfiguration apConfig,
         boolean paramBoolean) {
      try {
         Class<? extends WifiManager> localClass = mWifiManager.getClass();
         Class[] arrayOfClass = new Class[2];
         arrayOfClass[0] = WifiConfiguration.class;
         arrayOfClass[1] = Boolean.TYPE;
         Method localMethod = localClass.getMethod("setWifiApEnabled",
               arrayOfClass);
         WifiManager localWifiManager = mWifiManager;
         Object[] arrayOfObject = new Object[2];
         arrayOfObject[0] = apConfig;
         arrayOfObject[1] = Boolean.valueOf(paramBoolean);
         localMethod.invoke(localWifiManager, arrayOfObject);
         return;
      } catch (Exception localException) {
      }
 }