现附上一段代码,这段代码参考了很多人的并且进行了自己的补充和注释
public class MainActivity extends Activity {
private TextView netWork;
private TextView wifi;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
netWork=(TextView)this.findViewById(R.id.netWorkAvaliable);
wifi=(TextView)this.findViewById(R.id.wifiAvaliable);
testConnectivityManager();
}
public void testConnectivityManager() {
Context context = this.getApplicationContext();//获取应用上下文
// ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);//获取系统的连接服务
//NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();//获取网络的连接情况
WifiManager wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
if (wifiManager.isWifiEnabled()==true)
{
wifi.setText("wifi closing");
toggleWiFi(false);
}
stratWifiAp(wifiManager);
//if(activeNetInfo.getType()==ConnectivityManager.TYPE_WIFI){
//判断WIFI网
// wifi.setText("wifi setting");
// toggleWiFi(false);
// }
}
public void toggleWiFi(boolean status) {
WifiManager wifiManager = (WifiManager) this
.getSystemService(Context.WIFI_SERVICE);
if (status == true && !wifiManager.isWifiEnabled()) {
wifiManager.setWifiEnabled(true);
} else if (status == false && wifiManager.isWifiEnabled()) {
wifiManager.setWifiEnabled(false);
}
}
public void stratWifiAp(WifiManager wifiManager) {
Method method1 = null;
try {
method1 = wifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
WifiConfiguration netConfig = new WifiConfiguration();
//wifi热点名字
netConfig.SSID = "Hehyu";
netConfig.allowedAuthAlgorithms
.set(WifiConfiguration.AuthAlgorithm.OPEN);
netConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
netConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
netConfig.allowedKeyManagement
.set(WifiConfiguration.KeyMgmt.WPA_PSK);
netConfig.allowedPairwiseCiphers
.set(WifiConfiguration.PairwiseCipher.CCMP);
netConfig.allowedPairwiseCiphers
.set(WifiConfiguration.PairwiseCipher.TKIP);
netConfig.allowedGroupCiphers
.set(WifiConfiguration.GroupCipher.CCMP);
netConfig.allowedGroupCiphers
.set(WifiConfiguration.GroupCipher.TKIP);
//密码
netConfig.preSharedKey = "19921214";
method1.invoke(wifiManager, netConfig, true);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
因为时间比较晚了,明天再进行代码的补充和注释吧