我尝试了很多代码,所以找不到解决方案来更改wifi热点状态。有人能给我示例代码来打开和关闭wifi热点吗?
答案 0 :(得分:1)
对于API <26,Android SDK中没有公共API。但是您可以根据需要使用反射。
public boolean setWifiEnabled(WifiConfiguration wifiConfig, boolean enabled) {
WifiManager wifiManager;
try {
if (enabled) { //disables wifi hotspot if it's already enabled
wifiManager.setWifiEnabled(false);
}
Method method = wifiManager.getClass()
.getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
return (Boolean) method.invoke(wifiManager, wifiConfig, enabled);
} catch (Exception e) {
Log.e(this.getClass().toString(), "", e);
return false;
}
}
但是您将需要 WRITE_SYSTEM_SETTINGS 权限。在 manifest.xml
中声明 <uses-permission
android:name="android.permission.WRITE_SETTINGS"
tools:ignore="ProtectedPermissions"/>
在运行时询问权限。
private boolean showWritePermissionSettings() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
if (!Settings.System.canWrite(this)) {
Log.v("DANG", " " + !Settings.System.canWrite(this));
Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_WRITE_SETTINGS);
intent.setData(Uri.parse("package:" + this.getPackageName()));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
this.startActivity(intent);
return false;
}
}
return true; //Permission already given
}
对于API> = 26,您可以实现此solution。