需要權限
<!--wifi熱點權限-->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.OVERRIDE_WIFI_CONFIG" />
<!--移動數據權限-->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
/**
* 8.0 開啓wifi熱點方法
* @param apName wifi熱點帳號
* @param apPassword wifi熱點密碼
*/
public boolean setWifiAp(String apName, String apPassword) {
try {
//熱點的配置類
WifiConfiguration apConfig = new WifiConfiguration();
//配置熱點的名稱(可以在名字後面加點隨機數什麼的)
apConfig.SSID = apName;
apConfig.preSharedKey = apPassword;
//不設置密碼
apConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
//android 8.0開啓wifi熱點
if (Build.VERSION.SDK_INT >= 26) {
Method configMethod = mWifiManager.getClass().getMethod("setWifiApConfiguration", WifiConfiguration.class);
boolean isConfigured = (Boolean) configMethod.invoke(mWifiManager, apConfig);
method = mWifiManager.getClass().getMethod("startSoftAp", WifiConfiguration.class);
//返回熱點打開狀態
return (Boolean) method.invoke(mWifiManager, apConfig);
} else {
//通過反射調用設置熱點
method = mWifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, Boolean.TYPE);
//返回熱點打開狀態
return (Boolean) method.invoke(mWifiManager, apConfig, true);
}
} catch (NoSuchMethodException e) {
e.getMessage();
return false;
} catch (IllegalAccessException e) {
e.printStackTrace();
return false;
} catch (InvocationTargetException e) {
e.printStackTrace();
return false;
}
}
/**
* 關閉wifi 熱點
* @return
*/
public boolean closeWifiAp() {
//熱點的配置類
WifiConfiguration apConfig = new WifiConfiguration();
try {
//android 8.0關閉wifi熱點
if (Build.VERSION.SDK_INT >= 26) {
method = mWifiManager.getClass().getDeclaredMethod("stopSoftAp");
return (Boolean) method.invoke(mWifiManager);
} else {
method = mWifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, Boolean.TYPE);
//返回熱點關閉狀態
return (Boolean) method.invoke(mWifiManager, apConfig, false);
}
} catch (Exception e) {
e.getMessage();
return false;
}
}
/**
* 打開移動網絡
* @param context
* @param enabled 是否打開
*/
public void setMobileDataState(Context context, boolean enabled) {
TelephonyManager telephonyService = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
try {
Method setDataEnabled = telephonyService.getClass().getDeclaredMethod("setDataEnabled",boolean.class);
if (null != setDataEnabled) {
setDataEnabled.invoke(telephonyService, enabled);
}
} catch (Exception e) {
e.printStackTrace();
}
}