android.net.wifi.WifiManager Java Examples

The following examples show how to use android.net.wifi.WifiManager. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: WifiApManager.java    From PhoneProfilesPlus with Apache License 2.0 9 votes vote down vote up
@SuppressLint("PrivateApi")
WifiApManager(Context context) throws SecurityException, NoSuchMethodException {
    mWifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
    if (mWifiManager != null)
        wifiApEnabled = mWifiManager.getClass().getDeclaredMethod("isWifiApEnabled");
    /*if (PPApplication.logEnabled()) {
        PPApplication.logE("$$$ WifiAP", "WifiApManager.WifiApManager-mWifiManager=" + mWifiManager);
        PPApplication.logE("$$$ WifiAP", "WifiApManager.WifiApManager-wifiApEnabled=" + wifiApEnabled);
    }*/
    if (Build.VERSION.SDK_INT >= 26) {
        mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        packageName = context.getPackageName();
    }
    else {
        if (mWifiManager != null) {
            wifiControlMethod = mWifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
            wifiApConfigurationMethod = mWifiManager.getClass().getMethod("getWifiApConfiguration"/*,null*/);
            //wifiApState = mWifiManager.getClass().getMethod("getWifiApState");
        }
        /*if (PPApplication.logEnabled()) {
            PPApplication.logE("$$$ WifiAP", "WifiApManager.WifiApManager-wifiControlMethod=" + wifiControlMethod);
            PPApplication.logE("$$$ WifiAP", "WifiApManager.WifiApManager-wifiApConfigurationMethod=" + wifiApConfigurationMethod);
        }*/
    }
}
 
Example #2
Source File: Tethering.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@Override
public void onReceive(Context content, Intent intent) {
    final String action = intent.getAction();
    if (action == null) return;

    if (action.equals(UsbManager.ACTION_USB_STATE)) {
        handleUsbAction(intent);
    } else if (action.equals(CONNECTIVITY_ACTION)) {
        handleConnectivityAction(intent);
    } else if (action.equals(WifiManager.WIFI_AP_STATE_CHANGED_ACTION)) {
        handleWifiApAction(intent);
    } else if (action.equals(Intent.ACTION_CONFIGURATION_CHANGED)) {
        mLog.log("OBSERVED configuration changed");
        updateConfiguration();
    }
}
 
Example #3
Source File: DataStorage.java    From PacketSender-Android with MIT License 6 votes vote down vote up
public static boolean isWifiActive(Context ctx)
{
    WifiManager wifi = (WifiManager) ctx.getSystemService(ctx.WIFI_SERVICE);

    if(wifi.getWifiState() != WifiManager.WIFI_STATE_ENABLED )
    {

        return false;
    } else {

        if(getIP(ctx).equalsIgnoreCase("0.0.0.0"))
        {
            return false;

        } else {
            return true;
        }


    }
}
 
Example #4
Source File: ai.java    From MiBandDecompiled with Apache License 2.0 6 votes vote down vote up
protected final String p()
{
    if (m == null && a != null)
    {
        d = (WifiManager)a.getSystemService("wifi");
        if (d != null && d.getConnectionInfo() != null)
        {
            m = d.getConnectionInfo().getMacAddress();
            if (m != null && m.length() > 0)
            {
                m = m.replace(":", "");
            }
        }
    }
    if (m != null)
    {
        return m;
    } else
    {
        return "";
    }
}
 
Example #5
Source File: ConnectorUtils.java    From WifiUtils with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("UnusedReturnValue")
private static boolean checkForExcessOpenNetworkAndSave(@NonNull final ContentResolver resolver, @NonNull final WifiManager wifiMgr) {
    final List<WifiConfiguration> configurations = wifiMgr.getConfiguredNetworks();
    sortByPriority(configurations);

    boolean modified = false;
    int tempCount = 0;
    final int numOpenNetworksKept = Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1
            ? Settings.Secure.getInt(resolver, Settings.Global.WIFI_NUM_OPEN_NETWORKS_KEPT, 10)
            : Settings.Secure.getInt(resolver, Settings.Secure.WIFI_NUM_OPEN_NETWORKS_KEPT, 10);

    for (int i = configurations.size() - 1; i >= 0; i--) {
        final WifiConfiguration config = configurations.get(i);
        if (Objects.equals(ConfigSecurities.SECURITY_NONE, ConfigSecurities.getSecurity(config))) {
            tempCount++;
            if (tempCount >= numOpenNetworksKept) {
                modified = true;
                wifiMgr.removeNetwork(config.networkId);
            }
        }
    }
    return !modified || wifiMgr.saveConfiguration();

}
 
Example #6
Source File: ReplicationServiceTest.java    From sync-android with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public void setUp() {
    mMockContext = mock(Context.class);
    mMockPreferences = mock(SharedPreferences.class);
    when(mMockContext.getSharedPreferences("com.cloudant.preferences", Context.MODE_PRIVATE)).thenReturn(mMockPreferences);
    when(mMockContext.getPackageName()).thenReturn("cloudant.com.androidtest");
    when(mMockContext.getDir(anyString(), anyInt())).thenReturn(new File("/data/data/cloudant.com.androidtest/files"));
    when(mMockContext.getApplicationContext()).thenReturn(mMockContext);
    mMockPreferencesEditor = mock(SharedPreferences.Editor.class);
    when(mMockPreferences.edit()).thenReturn(mMockPreferencesEditor);
    mMockAlarmManager = mock(AlarmManager.class);
    mMockWifiManager = mock(WifiManager.class);
    mMockWifiLock = mock(WifiManager.WifiLock.class);
    mMockReplicationPolicyManager = mock(ReplicationPolicyManager.class);
    mMockReplicators = new Replicator[]{mock(Replicator.class)};
}
 
Example #7
Source File: WifiConnector.java    From Android with Apache License 2.0 6 votes vote down vote up
@Override
   public void onReceive(Context context, Intent intent) {
	
if (!WifiManager.SUPPLICANT_STATE_CHANGED_ACTION.equals(intent.getAction())) {
           return;
    }				
	
       mLock.lock();
	
       WifiInfo info = mWifiManager.getConnectionInfo();
       if ( info.getNetworkId()==mNetworkID && info.getSupplicantState() == SupplicantState.COMPLETED ) {
           mIsConnnected = true;
           mCondition.signalAll();			
}
	
       mLock.unlock();	
   }
 
Example #8
Source File: NetworkUtils.java    From AndroidModulePattern with Apache License 2.0 6 votes vote down vote up
/**
 * 打开或关闭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);
        }
    }
}
 
Example #9
Source File: OBConnectionManager.java    From GLEXP-Team-onebillion with Apache License 2.0 6 votes vote down vote up
public boolean isScanningDisabled ()
{
    WifiManager wifiManager = (WifiManager) MainActivity.mainActivity.getApplicationContext().getSystemService(MainActivity.WIFI_SERVICE);
    if (wifiManager.isScanAlwaysAvailable()) return false;
    //
    BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (bluetoothAdapter.isDiscovering()) return false;
    //
    return true;
}
 
Example #10
Source File: OBConnectionManager.java    From GLEXP-Team-onebillion with Apache License 2.0 6 votes vote down vote up
public void forgetAllNetworks()
{
    WifiManager wifiManager = (WifiManager) MainActivity.mainActivity.getApplicationContext().getSystemService(MainActivity.WIFI_SERVICE);
    List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
    //
    for( WifiConfiguration i : list )
    {
        // Please Note: the app cannot make the system forget wifi configurations that were placed by the user or other apps.
        // Just the ones that this app has set.
        wifiManager.removeNetwork(i.networkId);
        wifiManager.saveConfiguration();
    }
}
 
Example #11
Source File: AppNetworkMgr.java    From AndroidWallet with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 过滤扫描结果
 *
 * @param context
 * @param bssid
 * @return
 */
public static ScanResult getScanResultsByBSSID(Context context, String bssid) {
    WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    ScanResult scanResult = null;
    boolean f = wifiManager.startScan();
    if (!f) {
        getScanResultsByBSSID(context, bssid);
    }
    List<ScanResult> list = wifiManager.getScanResults();
    if (list != null) {
        for (int i = 0; i < list.size(); i++) {
            scanResult = list.get(i);
            if (scanResult.BSSID.equals(bssid)) {
                break;
            }
        }
    }
    return scanResult;
}
 
Example #12
Source File: BackgroundAudioService.java    From YouTube-In-Background with MIT License 6 votes vote down vote up
@SuppressLint("WifiManagerPotentialLeak")
@Override
public void onCreate()
{
    super.onCreate();
    context = getApplicationContext();
    currentVideo = new YouTubeVideo();
    audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    currentVideoPosition = -1;
    mediaButtonFilter.setPriority(1000); //this line sets receiver priority

    // Create the Wifi lock (this does not acquire the lock, this just creates it)
    this.wifiLock = ((WifiManager) context.getSystemService(Context.WIFI_SERVICE)).createWifiLock(WifiManager.WIFI_MODE_FULL, "YTinBG_lock");
    initMediaSessions();
    initPhoneCallListener();
}
 
Example #13
Source File: Settings.java    From Nimingban with Apache License 2.0 6 votes vote down vote up
public static String getMacFeedId() {
    WifiManager wifi = (WifiManager) sContext.getSystemService(Context.WIFI_SERVICE);
    WifiInfo info = wifi.getConnectionInfo();
    if (info == null) {
        return null;
    }

    String mac = info.getMacAddress();
    if (mac == null) {
        return null;
    }

    String id;
    try {
        MessageDigest digest = MessageDigest.getInstance("MD5");
        digest.update(mac.getBytes());
        id = bytesToHexString(digest.digest());
    } catch (NoSuchAlgorithmException e) {
        id = String.valueOf(mac.hashCode());
    }

    return id;
}
 
Example #14
Source File: WifiBaseActivity.java    From android-wifi-activity with Creative Commons Zero v1.0 Universal 6 votes vote down vote up
/**
 * Start connecting to specific wifi network
 */
protected void handleWIFI() {
    WifiManager wifi = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
    if (!wifi.isWifiEnabled()) {
        showWifiDisabledDialog();
    }
    else {
        if (!permisionLocationOn()) {
            setLocationPermission();
        } else {
            if (checkLocationTurnOn()) {
                connectToSpecificNetwork();
            }
        }
    }
}
 
Example #15
Source File: WifiAdmin.java    From cordova-plugin-wifi with MIT License 6 votes vote down vote up
private PluginResult executeEnableWifi(JSONArray inputs, CallbackContext callbackContext) {
  	Log.w(LOGTAG, "executeEnableWifi");

Context context = cordova.getActivity().getApplicationContext();
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);

boolean toEnable = true;
try {
	toEnable = inputs.getBoolean( 0 );
} catch (JSONException e) {
      Log.w(LOGTAG, String.format("Got JSON Exception: %s", e.getMessage()));
      return new PluginResult(Status.JSON_EXCEPTION);
}
      
wifiManager.setWifiEnabled( toEnable );
callbackContext.success();

  	return null;
  }
 
Example #16
Source File: PlatformNetworksManager.java    From 365browser with Apache License 2.0 6 votes vote down vote up
static VisibleWifi getConnectedWifi(Context context, WifiManager wifiManager) {
    if (!hasLocationAndWifiPermission(context)) {
        return VisibleWifi.NO_WIFI_INFO;
    }
    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
    if (wifiInfo == null) {
        return VisibleWifi.NO_WIFI_INFO;
    }
    String ssid = wifiInfo.getSSID();
    if (ssid == null || UNKNOWN_SSID.equals(ssid)) {
        // No SSID.
        ssid = null;
    } else {
        // Remove double quotation if ssid has double quotation.
        if (ssid.startsWith("\"") && ssid.endsWith("\"") && ssid.length() > 2) {
            ssid = ssid.substring(1, ssid.length() - 1);
        }
    }
    String bssid = wifiInfo.getBSSID();
    // It's connected, so use current time.
    return VisibleWifi.create(ssid, bssid, null, sTimeProvider.getCurrentTime());
}
 
Example #17
Source File: ConnectivityActivity.java    From RoMote with Apache License 2.0 6 votes vote down vote up
@Override
public void onResume() {
    super.onResume();

    if (!mNetworkMonitor.isConnectedToiWiFi() &&
            !mNetworkMonitor.isMobileAccessPointOn() &&
            mDialog == null) {
        showDialog();
    }

    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
    intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);

    registerReceiver(mConnectivityReceiver, intentFilter);
}
 
Example #18
Source File: Utils.java    From RPiCameraViewer with MIT License 6 votes vote down vote up
public static String getLocalIpAddress()
{
	String address = "";
	WifiManager manager = (WifiManager)App.getContext().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
	if (manager.isWifiEnabled())
	{
		WifiInfo wifiInfo = manager.getConnectionInfo();
		if (wifiInfo != null)
		{
			NetworkInfo.DetailedState state = WifiInfo.getDetailedStateOf(wifiInfo.getSupplicantState());
			if (state == NetworkInfo.DetailedState.CONNECTED || state == NetworkInfo.DetailedState.OBTAINING_IPADDR)
			{
				int ip = wifiInfo.getIpAddress();
				address = Formatter.formatIpAddress(ip);
			}
		}
	}
	return address;
}
 
Example #19
Source File: OBConnectionManager.java    From GLEXP-Team-onebillion with Apache License 2.0 6 votes vote down vote up
public String getCurrentWifiSSID()
{
    WifiManager wifiManager = (WifiManager) MainActivity.mainActivity.getApplicationContext().getSystemService(MainActivity.WIFI_SERVICE);
    WifiInfo info = wifiManager.getConnectionInfo ();
    String ssid = info.getSSID();
    if (info.getSupplicantState() != SupplicantState.COMPLETED)
    {
        MainActivity.log("OBConnectionManager:getCurrentWifiSSID. not connected to current wifi. returning null");
        return null;
    }
    if (ssid.charAt(0) == '"' && ssid.charAt(ssid.length() - 1) == '"')
    {
        return ssid.substring(1, ssid.length() - 1);
    }
    else
    {
        return ssid;
    }
}
 
Example #20
Source File: WifiApListProvider.java    From PrivacyStreams with Apache License 2.0 6 votes vote down vote up
@Override
protected void provide() {

    WifiManager wifiMgr = (WifiManager) this.getContext().getApplicationContext().getSystemService(Context.WIFI_SERVICE);

    if(wifiMgr.isWifiEnabled()) {
        Log.e("wifi","enabled");
        this.getContext().registerReceiver(this.wifiReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
        wifiMgr.startScan();
    }
    else{
        Log.e("wifi","not enabled");
        this.finish();
    }

}
 
Example #21
Source File: PickServerActivity.java    From android-vlc-remote with GNU General Public License v3.0 5 votes vote down vote up
private WifiInfo getConnectionInfo() {
    Object service = getSystemService(WIFI_SERVICE);
    WifiManager manager = (WifiManager) service;
    WifiInfo info = manager.getConnectionInfo();
    if (info != null) {
        SupplicantState state = info.getSupplicantState();
        if (state.equals(SupplicantState.COMPLETED)) {
            return info;
        }
    }
    return null;
}
 
Example #22
Source File: WifiapBroadcast.java    From WifiChat with GNU General Public License v2.0 5 votes vote down vote up
public void onReceive(Context paramContext, Intent paramIntent) {

        // wifi开关
        if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(paramIntent.getAction())) {
            int wifiState = paramIntent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 0);
            switch (wifiState) {
                case WifiManager.WIFI_STATE_DISABLED:
                case WifiManager.WIFI_STATE_ENABLED:
                    mListener.wifiStatusChange();
                    break;
            }
        }

        // 连接wifi
        else if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(paramIntent.getAction())) {
            mNetworkInfo = paramIntent.getParcelableExtra("networkInfo");

            /**
             * 当 DetailedState 变化为 CONNECTED 时,说明已连接成功,则通知Handler更新
             * 可避免WifiapActivity里出现重复获取IP的问题
             */
            if (mNetworkInfo.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
                mListener.WifiConnected();
            }
        }

    }
 
Example #23
Source File: WiFiUtil.java    From WiFiProxySwitcher with Apache License 2.0 5 votes vote down vote up
public boolean connectWiFi(String SSID, String password, int Type) {
    if (wifiManager.getWifiState() == WifiManager.WIFI_STATE_DISABLED) {
        wifiManager.setWifiEnabled(true);
    }
    WifiConfiguration config = createWiFiInfo(SSID, password, Type);
    return addNetwork(config);
}
 
Example #24
Source File: ContextUtils.java    From ProjectX with Apache License 2.0 5 votes vote down vote up
/**
 * 获取WIFI IP地址
 *
 * @param context Context
 * @return IP地址
 */
public static String getWifiIp(Context context) {
    final WifiManager manager = (WifiManager) context.getApplicationContext()
            .getSystemService(Context.WIFI_SERVICE);
    if (manager == null)
        return "0.0.0.0";
    final DhcpInfo info = manager.getDhcpInfo();
    if (info == null)
        return "0.0.0.0";
    final int ip = info.ipAddress;
    return (0xFF & ip) + "." + (0xFF & ip >> 8) + "." + (0xFF & ip >> 16) + "."
            + (0xFF & ip >> 24);
}
 
Example #25
Source File: TinfoilNET.java    From ns-usbloader-mobile with GNU General Public License v3.0 5 votes vote down vote up
private void resolvePhoneIp() throws Exception{
    WifiManager wm = (WifiManager) context.getApplicationContext().getSystemService(WIFI_SERVICE);
    if (wm == null)
        throw new Exception("NET: Unable to auto-resolve IP address.");

    int intIp = wm.getConnectionInfo().getIpAddress();
    phoneIp = String.format(Locale.US, "%d.%d.%d.%d",
            (intIp & 0xff),
            (intIp >> 8 & 0xff),
            (intIp >> 16 & 0xff),
            (intIp >> 24 & 0xff));
    if (phoneIp.equals("0.0.0.0"))
        throw new Exception("NET: Unable to auto-resolve IP address (0.0.0.0)");
}
 
Example #26
Source File: WiFiScanner.java    From esp-idf-provisioning-android with Apache License 2.0 5 votes vote down vote up
@RequiresPermission(Manifest.permission.CHANGE_WIFI_STATE)
public WiFiScanner(Context context, WiFiScanListener wiFiScanListener) {

    this.context = context;
    this.wiFiScanListener = wiFiScanListener;
    results = new ArrayList<>();
    wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);

    if (!wifiManager.isWifiEnabled()) {

        wifiManager.setWifiEnabled(true);
    }
}
 
Example #27
Source File: WifiConfigManager.java    From barcodescanner-lib-aar with MIT License 5 votes vote down vote up
private static void changeNetworkWPA(WifiManager wifiManager, WifiParsedResult wifiResult) {
  WifiConfiguration config = changeNetworkCommon(wifiResult);
  // Hex passwords that are 64 bits long are not to be quoted.
  config.preSharedKey = quoteNonHex(wifiResult.getPassword(), 64);
  config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
  config.allowedProtocols.set(WifiConfiguration.Protocol.WPA); // For WPA
  config.allowedProtocols.set(WifiConfiguration.Protocol.RSN); // For WPA2
  config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
  config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
  config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
  config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
  config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
  config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
  updateNetwork(wifiManager, config);
}
 
Example #28
Source File: AppNetworkMgr.java    From AndroidWallet with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 判断Wifi是否打开,需要ACCESS_WIFI_STATE权限
 *
 * @param context 上下文
 * @return true:打开;false:关闭
 */
public static boolean isWifiOpen(Context context) throws Exception {
    int wifiState = getWifiState(context);
    return wifiState == WifiManager.WIFI_STATE_ENABLED ||
            wifiState == WifiManager.WIFI_STATE_ENABLING
            ? true
            : false;
}
 
Example #29
Source File: DeviceNetworkStatus.java    From product-emm with Apache License 2.0 5 votes vote down vote up
private DeviceNetworkStatus(final Context context) {
    this.context = context;
    wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    receiverWifi = new WifiReceiver();

    // Register broadcast receiver
    // Broacast receiver will automatically call when number of wifi connections changed
    context.registerReceiver(receiverWifi, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
    // start scanning wifi
    startWifiScan();

    info = getNetworkInfo(context);
    mapper = new ObjectMapper();
}
 
Example #30
Source File: NetworkScoreService.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
@Override
public WifiInfo get() {
    WifiManager wifiManager = mContext.getSystemService(WifiManager.class);
    if (wifiManager != null) {
        return wifiManager.getConnectionInfo();
    }
    Log.w(TAG, "WifiManager is null, failed to return the WifiInfo.");
    return null;
}