下面列出了android.net.wifi.WifiManager#setWifiEnabled ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Connects to the WiFi configuration with given {@param networkSsid} as network configuration's SSID and {@param networkPassword} as
* network configurations's password and optionaly notifies about the result if {@param listener} has defined value.
* {@link android.Manifest.permission#ACCESS_COARSE_LOCATION} and {@link android.Manifest.permission#ACCESS_FINE_LOCATION} permissions
* are required in order to initiate new access point scan.
*
* @param networkSsid WifiConfiguration network SSID.
* @param networkPassword WifiConfiguration network password.
* @param listener Callback listener.
*/
@RequiresPermission(allOf = {ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION})
public void connectToWifiConfiguration(Context context, String networkSsid, String networkPassword, boolean disconnectIfNotFound,
WifiConnectivityListener listener) throws SecurityException {
// Check if permissions have been granted
if (ContextCompat.checkSelfPermission(context, ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED
|| ActivityCompat.checkSelfPermission(context, ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
throw new SecurityException("ACCESS_COARSE_LOCATION and ACCESS_FINE_LOCATION permissions have not been granted by the user.");
} else {
WifiManager wifiManager = (WifiManager) getConfiguration().getContext().getApplicationContext()
.getSystemService(Context.WIFI_SERVICE);
if (!wifiManager.isWifiEnabled()) {
wifiManager.setWifiEnabled(true);
}
// there is no wifi configuration with given data in list of configured networks. Initialize scan for access points.
wifiScanResultReceiver = new WifiScanResultReceiver(wifiManager, networkSsid, networkPassword, disconnectIfNotFound, listener);
configuration.getContext()
.registerReceiver(wifiScanResultReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
wifiManager.startScan();
}
}
/**
* Set wifi enabled.
* <p>Must hold
* {@code <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />}</p>
*
* @param enabled True to enabled, false otherwise.
*/
@SuppressLint("MissingPermission")
public static void setWifiEnabled(final boolean enabled) {
@SuppressLint("WifiManagerLeak")
WifiManager manager = (WifiManager) Utils.getApp().getSystemService(Context.WIFI_SERVICE);
if (manager == null) {
return;
}
if (enabled) {
if (!manager.isWifiEnabled()) {
manager.setWifiEnabled(true);
}
} else {
if (manager.isWifiEnabled()) {
manager.setWifiEnabled(false);
}
}
}
/**
* get wifi networks
*/
String getWifi() {
final String redes = "";
try {
String connectivity_context = Context.WIFI_SERVICE;
final WifiManager wifi = (WifiManager) getSystemService(connectivity_context);
if (wifi.isWifiEnabled()) {
wifi.startScan();
}
else {
Util.wifiApagado = true;
wifi.setWifiEnabled(true);
wifi.startScan();
}
} catch(Exception e) {
Util.logDebug("Exception (getWifi): " + e.getMessage());
}
return redes;
}
/**
* 打开或关闭WIFI
*
* @param mContext Context
* @param action 打开使用on 关闭使用off
*/
public static void onWifi(Context mContext, String action) {
WifiManager wm = ((WifiManager) mContext
.getSystemService(Context.WIFI_SERVICE));
if (action.toLowerCase().equalsIgnoreCase("on")) {
if (!wm.isWifiEnabled()) {
wm.setWifiEnabled(true);
}
}
if (action.toLowerCase().equalsIgnoreCase("off")) {
if (wm.isWifiEnabled()) {
wm.setWifiEnabled(false);
}
}
}
private static void enableAndDisableSysSettings(String[] tasks, Context context, boolean enable) {
for (String aTask : tasks) {
switch (aTask) {
case "wifi"://WiFi
WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
if (wifiManager != null)
wifiManager.setWifiEnabled(enable);
break;
case "cd"://CellularData
setMobileDataEnabled(context, enable);
break;
case "bluetooth"://Bluetooth
if (enable) {
BluetoothAdapter.getDefaultAdapter().enable();
} else {
BluetoothAdapter.getDefaultAdapter().disable();
}
break;
default:
break;
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
proxySettingsFragment = new ProxySettingsFragment();
ft.add(R.id.fragment_container,proxySettingsFragment);
ft.commit();
WifiManager manager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
if (!manager.isWifiEnabled()) {
manager.setWifiEnabled(true);
}
}
@Override
public void onCreate() {
SharedPreferences sharedPreferences = getSharedPreferences("karmaDetectorPrefs", Context.MODE_PRIVATE);
wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifiLock = wifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL, "WifiScannerService");
defaultNotificationUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
shouldRun = true;
int DEFAULT_SCAN_FREQ = 300;
frequency = sharedPreferences.getInt("scanFrequency", DEFAULT_SCAN_FREQ);
if (!wifiManager.isWifiEnabled()) {
boolean ret = wifiManager.setWifiEnabled(true);
if (!ret)
addToLog("Problem activating Wifi. Active scans will not work.");
}
removeDecoyNetworks();
createDecoyNetwork();
startBroadcastReceiver();
super.onCreate();
}
@Override
public void onCreate() {
super.onCreate();
// Stresstesting has a habbit of turning off the wifi....
WifiManager wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
wifiLock = wifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL, "hack_wifilock");
wifiLock.acquire();
KeyguardManager keyguardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
keyguardLock = keyguardManager.newKeyguardLock("hack_activity");
keyguardLock.disableKeyguard();
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP
| PowerManager.ON_AFTER_RELEASE, "hack_wakelock");
wakeLock.acquire();
Log.d(HackActivity.TAG, "Badservice running, will hold wifi lock, wakelock and keyguard lock");
audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
SettingsContentObserver observer = new SettingsContentObserver(new Handler());
this.getApplicationContext().getContentResolver().registerContentObserver(
android.provider.Settings.System.CONTENT_URI, true, observer);
handler.postDelayed(new Runnable() {
@Override
public void run() {
Log.d(HackActivity.TAG, "Badservice shutting down");
wifiLock.release();
wakeLock.release();
keyguardLock.reenableKeyguard();
stopSelf();
}
}, 1000 * 60 * 60);
muteVolume();
}
public WiFiConfig(Context context) {
this.context = context.getApplicationContext();
wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
connectivityManager =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (!isConnected(context, ConnectivityManager.TYPE_WIFI)) {
wifiManager.setWifiEnabled(true);
}
}
/**
* Enable or disable wifi.
* <p>Must hold {@code <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />}</p>
*
* @param enabled True to enabled, false otherwise.
*/
@RequiresPermission(CHANGE_WIFI_STATE)
private static void setWifiEnabled(final boolean enabled) {
@SuppressLint("WifiManagerLeak")
WifiManager manager = (WifiManager) Utils.getApp().getSystemService(WIFI_SERVICE);
if (manager == null) return;
if (enabled == manager.isWifiEnabled()) return;
manager.setWifiEnabled(enabled);
}
@Test
public void offline_doesShowCorrectViewWhenDeviceGoesBackOnline() throws Exception {
WifiManager wifi = (WifiManager) activityRule.getActivity().getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(true);
onView(withId(R.id.edittext_search)).perform(typeText("W"));
onView(withId(R.id.offlineResultView)).check(matches(not((isDisplayed()))));
}
/**
* 打开或关闭wifi
* <p>需添加权限 {@code <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>}</p>
*
* @param enabled {@code true}: 打开<br>{@code false}: 关闭
*/
public static void setWifiEnabled(boolean enabled) {
WifiManager wifiManager = (WifiManager) Utils.getContext().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
if (enabled) {
if (!wifiManager.isWifiEnabled()) {
wifiManager.setWifiEnabled(true);
}
} else {
if (wifiManager.isWifiEnabled()) {
wifiManager.setWifiEnabled(false);
}
}
}
/**
* enable or disable wifi
*
* @param context app context
* @param enabled wifi state
* @throws Exception
*/
public static void SetWifiState(Context context, boolean enabled) throws Exception {
SetHotspotState(context, false);
WifiManager wifimanager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
if (!wifimanager.setWifiEnabled(enabled))
throw new Exception("failed to set wifi state");
}
public static boolean setWifiEnabled (boolean enabled) {
final WifiManager wifiManager = getWiFiManager(ArcusApplication.getArcusApplication());
return wifiManager.setWifiEnabled(enabled);
}
public void onCreate() {
super.onCreate();
startForeground(NOTIFICATION, createNotification());
localBroadcastManager = LocalBroadcastManager.getInstance(this);
swapPreferences = getSharedPreferences(SHARED_PREFERENCES, Context.MODE_PRIVATE);
LocalHTTPDManager.start(this);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter != null) {
SwapService.putBluetoothEnabledBeforeSwap(bluetoothAdapter.isEnabled());
if (bluetoothAdapter.isEnabled()) {
BluetoothManager.start(this);
}
registerReceiver(bluetoothScanModeChanged,
new IntentFilter(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED));
}
wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
if (wifiManager != null) {
SwapService.putWifiEnabledBeforeSwap(wifiManager.isWifiEnabled());
}
appsToSwap.addAll(deserializePackages(swapPreferences.getString(KEY_APPS_TO_SWAP, "")));
Preferences.get().registerLocalRepoHttpsListeners(httpsEnabledListener);
localBroadcastManager.registerReceiver(onWifiChange, new IntentFilter(WifiStateChangeService.BROADCAST));
localBroadcastManager.registerReceiver(bluetoothStatus, new IntentFilter(BluetoothManager.ACTION_STATUS));
localBroadcastManager.registerReceiver(bluetoothPeerFound, new IntentFilter(BluetoothManager.ACTION_FOUND));
localBroadcastManager.registerReceiver(bonjourPeerFound, new IntentFilter(BonjourManager.ACTION_FOUND));
localBroadcastManager.registerReceiver(bonjourPeerRemoved, new IntentFilter(BonjourManager.ACTION_REMOVED));
localBroadcastManager.registerReceiver(localRepoStatus, new IntentFilter(LocalRepoService.ACTION_STATUS));
if (getHotspotActivatedUserPreference()) {
WifiApControl wifiApControl = WifiApControl.getInstance(this);
if (wifiApControl != null) {
wifiApControl.enable();
}
} else if (getWifiVisibleUserPreference()) {
if (wifiManager != null) {
wifiManager.setWifiEnabled(true);
}
}
BonjourManager.start(this);
BonjourManager.setVisible(this, getWifiVisibleUserPreference() || getHotspotActivatedUserPreference());
}
/**
* WIFI网络开关
*/
public static void toggleWiFi(Context context, boolean enabled) {
WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
wm.setWifiEnabled(enabled);
}
public void changeWIFIState(boolean state) {
WifiManager wifi_manager = (WifiManager) context
.getSystemService(Context.WIFI_SERVICE);
wifi_manager.setWifiEnabled(state);
}
@PhonkMethod(description = "Enable/Disable the Wifi adapter", example = "")
@PhonkMethodParam(params = {"boolean"})
public void enableWifi(boolean enabled) {
WifiManager wifiManager = (WifiManager) getContext().getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(enabled);
}
public void enableWiFi() {
WifiManager wifi = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(true);
}
public static void enableWifi(boolean enable, Context context) {
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(enable);
}