权限
//允许程序改变Wi-Fi连接状态
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
//允许程序访问Wi-Fi网络状态信息
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
热点封装类
package com.example.thrdemo;
import android.content.Context;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import java.lang.reflect.Method;
/**
* 热点类
* Created by yk on 2018/7/10.
*/
public class Hotspot {
WifiManager wifiManager;
public Hotspot(Context context) {
wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
}
/**
* 设置热点状态
*
* @param HotspotName 热点名称
* @param enabled true:打开热点;false:关闭热点
* @return 是否设置成功
*/
public boolean setWifiApEnabled(String HotspotName, String HotspotPwd, boolean enabled) {
if (wifiManager == null)
return false;
if (wifiManager.isWifiEnabled()) { // disable WiFi in any case
// wifi和热点不能同时打开,所以打开热点的时候需要关闭wifi
wifiManager.setWifiEnabled(false);
}
try {
// 热点的配置类
WifiConfiguration apConfig = new WifiConfiguration();
// 配置热点的名称
apConfig.SSID = HotspotName;
// 配置热点的密码
apConfig.preSharedKey = HotspotPwd;
apConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
// 通过反射调用设置热点
Method method = wifiManager.getClass().getMethod(
"setWifiApEnabled", WifiConfiguration.class, Boolean.TYPE);
// 返回热点打开状态
return (Boolean) method.invoke(wifiManager, apConfig, enabled);
} catch (Exception e) {
return false;
}
}
}