Android的开启/关闭WiFi热点编程 [英] Android turn On/Off WiFi HotSpot programmatically
本文介绍了Android的开启/关闭WiFi热点编程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有一个API来开启/关闭WiFi热点在Android编程?
Is there an API to turn On/Off the WiFi HotSpot on Android programmatically?
我应该方法,我应该叫把它开/关?
What should methods I should call to turn it On/Off?
更新:有这个选项有热点激活,并且只要打开/关闭无线网络,但是这不是我一个很好的解决方案。
UPDATE:There's this option to have the HotSpot enabled, and just turn On/Off the WiFi, but this is not a good solution for me.
推荐答案
使用下面的类来更改/检查WiFi热点设置:
import android.content.*;
import android.net.wifi.*;
import java.lang.reflect.*;
public class ApManager {
//check whether wifi hotspot on or off
public static boolean isApOn(Context context) {
WifiManager wifimanager = (WifiManager) context.getSystemService(context.WIFI_SERVICE);
try {
Method method = wifimanager.getClass().getDeclaredMethod("isWifiApEnabled");
method.setAccessible(true);
return (Boolean) method.invoke(wifimanager);
}
catch (Throwable ignored) {}
return false;
}
// toggle wifi hotspot on or off
public static boolean configApState(Context context) {
WifiManager wifimanager = (WifiManager) context.getSystemService(context.WIFI_SERVICE);
WifiConfiguration wificonfiguration = null;
try {
// if WiFi is on, turn it off
if(isApOn(context)) {
wifimanager.setWifiEnabled(false);
}
Method method = wifimanager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
method.invoke(wifimanager, wificonfiguration, !isApOn(context));
return true;
}
catch (Exception e) {
e.printStackTrace();
}
return false;
}
} // end of class
您需要添加以下到您的AndroidMainfest的权限:
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
从任何地方使用该独立ApManager类,如下所示:
ApManager.isApOn(YourActivity.this); // check Ap state :boolean
ApManager.configApState(YourActivity.this); // change Ap state :boolean
希望这会帮助别人
这篇关于Android的开启/关闭WiFi热点编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文