android.net.wifi.WifiManager#setWifiEnabled ( )源码实例Demo

下面列出了android.net.wifi.WifiManager#setWifiEnabled ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: android_connectionbuddy   文件: ConnectionBuddy.java
/**
 * 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();
    }
}
 
源代码2 项目: AcgClub   文件: NetworkUtils.java
/**
 * 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);
    }
  }
}
 
源代码3 项目: ownmdm   文件: LocAlarmService.java
/**
* 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;
  }
 
源代码4 项目: NonViewUtils   文件: Common.java
/**
 * 打开或关闭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);
        }
    }
}
 
源代码5 项目: FreezeYou   文件: TasksUtils.java
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;
        }
    }
}
 
源代码6 项目: WiFiProxySwitcher   文件: MainActivity.java
@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);
    }
}
 
源代码7 项目: karmadetector   文件: WifiScannerService.java
@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();
}
 
源代码8 项目: android_emulator_hacks   文件: Badservice.java
@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();
}
 
源代码9 项目: product-emm   文件: WiFiConfig.java
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);
    }
}
 
源代码10 项目: AndroidUtilCode   文件: DeviceUtils.java
/**
 * 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()))));
}
 
源代码12 项目: AndroidModulePattern   文件: NetworkUtils.java
/**
 * 打开或关闭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);
        }
    }
}
 
源代码13 项目: SimpleSmsRemote   文件: WifiUtils.java
/**
 * 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");
}
 
源代码14 项目: arcusandroid   文件: PhoneWifiHelper.java
public static boolean setWifiEnabled (boolean enabled) {
    final WifiManager wifiManager = getWiFiManager(ArcusApplication.getArcusApplication());
    return wifiManager.setWifiEnabled(enabled);
}
 
源代码15 项目: fdroidclient   文件: SwapService.java
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());
}
 
源代码16 项目: TikTok   文件: NetworkUtil.java
/**
 * WIFI网络开关
 */
public static void toggleWiFi(Context context, boolean enabled) {
    WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    wm.setWifiEnabled(enabled);
}
 
源代码17 项目: FoodOrdering   文件: NetWorkTool.java
public void changeWIFIState(boolean state) {
    WifiManager wifi_manager = (WifiManager) context
            .getSystemService(Context.WIFI_SERVICE);
    wifi_manager.setWifiEnabled(state);
}
 
源代码18 项目: PHONK   文件: PNetwork.java
@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);
}
 
源代码19 项目: ForceDoze   文件: ForceDozeService.java
public void enableWiFi() {
    WifiManager wifi = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
    wifi.setWifiEnabled(true);
}
 
源代码20 项目: Bluefruit_LE_Connect_Android   文件: BleUtils.java
public static void enableWifi(boolean enable, Context context) {
    WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    wifiManager.setWifiEnabled(enable);
}