開啟WIFI:
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
WifiManager wifi =(WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(true);
}
});
關閉WIFI:
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
WifiManager wifi = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(false);
}
});
獲得WIFI狀态:
button3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
WifiManager wifi = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
int wifiState = wifi.getWifiState();
Toast.makeText(mContext, "狀态是"+wifiState, Toast.LENGTH_SHORT).show();
}
});
最後記得要在注冊檔案中加上權限
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>