Java Code Examples for android.net.wifi.WifiManager#startScan()

The following examples show how to use android.net.wifi.WifiManager#startScan() . 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: 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 2
Source File: WifiInfo.java    From MobileInfo with Apache License 2.0 6 votes vote down vote up
static void getWifiList(final Context context, final WifiScanListener wifiScanListener) {
    if (wifiScanListener == null) {
        throw new NullPointerException("the WifiScanListener is null");
    }
    final long startTime = System.currentTimeMillis();
    final WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    final WifiBean wifiBean = new WifiBean();
    if (wifiManager == null) {
        wifiScanListener.onResult(wifiBean.toJSONObject());
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M&&context.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        wifiScanListener.onResult(wifiBean.toJSONObject());
    }
    BroadcastReceiver wifiScanReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context c, Intent intent) {
            context.unregisterReceiver(this);
            scanSuccess(wifiManager, wifiBean, startTime, wifiScanListener);
        }
    };
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
    context.registerReceiver(wifiScanReceiver, intentFilter);
    wifiManager.startScan();
}
 
Example 3
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 4
Source File: WifiDirectHandler.java    From WiFi-Buddy with MIT License 6 votes vote down vote up
/**
 * Registers the Wi-Fi manager, registers the app with the Wi-Fi P2P framework, registers the
 * P2P BroadcastReceiver, and registers a local BroadcastManager
 */
@Override
public void onCreate() {
    super.onCreate();
    Log.i(TAG, "Creating WifiDirectHandler");

    // Registers the Wi-Fi Manager and the Wi-Fi BroadcastReceiver
    wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
    registerWifiReceiver();

    // Scans for available Wi-Fi networks
    wifiManager.startScan();

    if (wifiManager.isWifiEnabled()) {
        Log.i(TAG, "Wi-Fi enabled on load");
    } else {
        Log.i(TAG, "Wi-Fi disabled on load");
    }

    // Registers a local BroadcastManager that is used to broadcast Intents to Activities
    localBroadcastManager = LocalBroadcastManager.getInstance(this);
    Log.i(TAG, "WifiDirectHandler created");
}
 
Example 5
Source File: ConnectionBuddy.java    From android_connectionbuddy with Apache License 2.0 6 votes vote down vote up
/**
 * 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();
    }
}
 
Example 6
Source File: PhoneWifiHelper.java    From arcusandroid with Apache License 2.0 6 votes vote down vote up
/**
 * Invokes a callback containing all of the currently available WiFi networks.
 *
 * @param context
 * @param callback
 */
public static void scanForAvailableNetworks(final Context context, final WifiScanCompleteListener callback) {
    final WifiManager wifiManager = getWiFiManager(context);

    BroadcastReceiver mWifiScanReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context c, Intent intent) {
            if (intent.getAction().equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
                new Handler(Looper.getMainLooper()).post(() -> callback.onWifiScanComplete(toAvailableNetworkModels(wifiManager.getScanResults())));
            }

            context.unregisterReceiver(this);
        }
    };

    context.registerReceiver(mWifiScanReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
    wifiManager.startScan();
}
 
Example 7
Source File: WifiBase.java    From android-wifi-activity with Creative Commons Zero v1.0 Universal 6 votes vote down vote up
/**
 * Start to connect to a specific wifi network
 */
private void connectToSpecificNetwork() {
    final WifiManager wifi = (WifiManager) getContext().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
    ConnectivityManager cm = (ConnectivityManager) getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    WifiInfo wifiInfo = wifi.getConnectionInfo();
    if (networkInfo.isConnected() && wifiInfo.getSSID().replace("\"", "").equals(getWifiSSID())) {
        return;
    }
    else {
        wifi.disconnect();
    }
    progressDialog = ProgressDialog.show(getContext(), getContext().getString(R.string.connecting), String.format(getContext().getString(R.string.connecting_to_wifi), getWifiSSID()));
    taskHandler = worker.schedule(new TimeoutTask(), getSecondsTimeout(), TimeUnit.SECONDS);
    scanReceiver = new ScanReceiver();
    getContext().registerReceiver(scanReceiver
            , new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
    wifi.startScan();
}
 
Example 8
Source File: WifiBaseActivity.java    From android-wifi-activity with Creative Commons Zero v1.0 Universal 6 votes vote down vote up
/**
 * Start to connect to a specific wifi network
 */
private void connectToSpecificNetwork() {
    final WifiManager wifi = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
    ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    WifiInfo wifiInfo = wifi.getConnectionInfo();
    if (networkInfo.isConnected() && wifiInfo.getSSID().replace("\"", "").equals(getWifiSSID())) {
        return;
    }
    else {
        wifi.disconnect();
    }
    progressDialog = ProgressDialog.show(this, getString(R.string.connecting), String.format(getString(R.string.connecting_to_wifi), getWifiSSID()));
    taskHandler = worker.schedule(new TimeoutTask(), getSecondsTimeout(), TimeUnit.SECONDS);
    scanReceiver = new ScanReceiver();
    registerReceiver(scanReceiver
            , new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
    wifi.startScan();
}
 
Example 9
Source File: LocAlarmService.java    From ownmdm with GNU General Public License v2.0 6 votes vote down vote up
/**
* 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;
  }
 
Example 10
Source File: WakelockHandler.java    From privacypolice with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    Log.v("PrivacyPolice", "Waking up because of alarm");
    // Start a Wi-Fi scan
    WifiManager wifiManager =  (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    wifiManager.startScan();
}
 
Example 11
Source File: PreferencesActivity.java    From privacypolice with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)
{
    // Perform a rescan every time a preference has changed
    Log.v("PrivacyPolice", "Initiating rescan because preference " + key + " changed");
    try {
        // getApplicationContext() to prevent memory leaks on devices < Android N
        WifiManager wifiManager = (WifiManager) getActivity().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        wifiManager.startScan();
    } catch (NullPointerException npe) {
        Log.e("PrivacyPolice", "Could not get WifiManager from within prefsFragment");
    }
}
 
Example 12
Source File: PermissionChangeReceiver.java    From privacypolice with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    ctx = context;
    prefs = new PreferencesStorage(ctx);

    // Remove the notification that was used to make the decision
    removeNotification();

    boolean enable = intent.getBooleanExtra("enable", true);
    String SSID = intent.getStringExtra("SSID");
    String BSSID = intent.getStringExtra("BSSID");

    if (SSID == null || BSSID == null) {
        Log.e("PrivacyPolice", "Could not set permission because SSID or BSSID was null!");
        return;
    }

    Log.d("PrivacyPolice", "Permission change: " + SSID + " " + BSSID + " " + enable);

    if (enable) {
        prefs.addAllowedBSSIDsForLocation(SSID);
        // initiate rescan, to make sure our algorithm enables the network, and to make sure
        // that Android connects to it
        WifiManager wifiManager = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE);
        wifiManager.startScan();
    } else
        prefs.addBlockedBSSID(SSID, BSSID);
}
 
Example 13
Source File: WifiSignalStrengthChangeReceiver.java    From NetworkEvents with Apache License 2.0 5 votes vote down vote up
@Override public void onReceive(Context context, Intent intent) {
  // We need to start WiFi scan after receiving an Intent
  // in order to get update with fresh data as soon as possible
  WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
  wifiManager.startScan();
  onPostReceive();
}
 
Example 14
Source File: NetworkEvents.java    From NetworkEvents with Apache License 2.0 5 votes vote down vote up
/**
 * Registers NetworkEvents.
 * It should be executed in onCreate() method in activity
 * or during creating instance of class extending Application.
 */
public void register() {
  registerNetworkConnectionChangeReceiver();
  registerInternetConnectionChangeReceiver();

  if (wifiAccessPointsScanEnabled) {
    registerWifiSignalStrengthChangeReceiver();
    // start WiFi scan in order to refresh access point list
    // if this won't be called WifiSignalStrengthChanged may never occur
    WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    wifiManager.startScan();
  }
}
 
Example 15
Source File: MainActivity.java    From DeAutherDroid with Apache License 2.0 4 votes vote down vote up
private void showScanResults() {

        View scanView = getLayoutInflater().inflate(R.layout.view_list, null);

        listView = scanView.findViewById(R.id.list);

        WifiManager manager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);

        if (manager != null) {
            manager.startScan();
        }

        Handler handlerX = new Handler();
        handlerX.post(new Runnable() {
            @Override
            public void run() {
                WifiUtils.withContext(getApplicationContext()).scanWifi(results -> {
                    List<String> arrayWIFIList = new ArrayList<>();
                    ScanResult result;
                    for (int i = 0; i < results.size(); i++) {
                        result = results.get(i);

                        Log.v(TAG, result.toString());
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                            arrayWIFIList.add(i, result.SSID + "[" + (double) result.frequency / 1000 + "GHz" + "/" + result.level + "dBm" + "]"
                                    + result.capabilities + getChannelWidth(result.channelWidth));
                        } else {
                            arrayWIFIList.add(i, result.SSID + "[" + (double) result.frequency / 1000 + "GHz" + "/" + result.level + "dBm" + "]"
                                    + result.capabilities);
                        }
                    }

                    String[] stringArray = arrayWIFIList.toArray(new String[0]);

                    ArrayAdapter<?> adapter = new ArrayAdapter<Object>(MainActivity.this, R.layout.list_text, R.id.textList, stringArray);

                    adapter.notifyDataSetChanged();
                    listView.setAdapter(adapter);

                }).start();
                handlerX.postDelayed(this, TimeUnit.SECONDS.toMillis(10));
            }
        });

        if (Prefs.getInstance(getBaseContext()).isWIFIRand()) {
            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (listView.getChildCount() > 0) {
                        for (int i = 0; i < listView.getChildCount(); i++) {
                            SecureRandom random = new SecureRandom(); /*  Just some beautifying */
                            int color = Color.argb(255, random.nextInt(200), random.nextInt(200), random.nextInt(255));
                            ((TextView) listView.getChildAt(i)).setTextColor(color);
                        }
                    }
                    handler.postDelayed(this, 250);
                }
            }, 100);
        }


        if (!MainActivity.this.isFinishing()) {
            new AlertDialog.Builder(MainActivity.this)
                    .setView(scanView)
                    .setTitle("WiFi Scan-results (Local)")
                    .setCancelable(false)
                    .setOnDismissListener(dialog -> {

                    })
                    .setNeutralButton("Help", (dialog, which) -> new AlertDialog.Builder(MainActivity.this)
                            .setMessage(R.string.help_scan)
                            .setCancelable(false)
                            .setPositiveButton("Okay", null)
                            .show())
                    .setPositiveButton("Close / Stop Scan", null).show();
        }
    }
 
Example 16
Source File: NetUtils.java    From Gizwits-SmartBuld_Android with MIT License 2 votes vote down vote up
/**
 * 用来获得手机扫描到的所有wifi的信息.
 *
 * @param c
 *            上下文
 * @return the current wifi scan result
 */
static public List<ScanResult> getCurrentWifiScanResult(Context c) {
	WifiManager wifiManager = (WifiManager) c.getSystemService(Context.WIFI_SERVICE);
	wifiManager.startScan();
	return wifiManager.getScanResults();
}
 
Example 17
Source File: NetUtils.java    From gokit-android with MIT License 2 votes vote down vote up
/**
 * 用来获得手机扫描到的所有wifi的信息.
 *
 * @param c
 *            上下文
 * @return the current wifi scan result
 */
static public List<ScanResult> getCurrentWifiScanResult(Context c) {
	WifiManager wifiManager = (WifiManager) c.getSystemService(Context.WIFI_SERVICE);
	wifiManager.startScan();
	return wifiManager.getScanResults();
}
 
Example 18
Source File: NetUtils.java    From GOpenSource_AppKit_Android_AS with MIT License 2 votes vote down vote up
/**
 * 用来获得手机扫描到的所有wifi的信息.
 *
 * @param c
 *            上下文
 * @return the current wifi scan result
 */
static public List<ScanResult> getCurrentWifiScanResult(Context c) {
	WifiManager wifiManager = (WifiManager) c.getSystemService(Context.WIFI_SERVICE);
	wifiManager.startScan();
	return wifiManager.getScanResults();
}
 
Example 19
Source File: AppNetworkMgr.java    From AndroidWallet with GNU General Public License v3.0 2 votes vote down vote up
/**
 * 获取wifi列表
 *
 * @param context
 * @return
 */
public static List<ScanResult> getWifiScanResults(Context context) {
    WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    return wifiManager.startScan() ? wifiManager.getScanResults() : null;
}