WiFiUtils


Source link: https://github.com/ThanosFisherman/WifiUtils

WifiUtils

WiFi Utils is a library that provides a set of convenience methods for managing WiFi State, WiFi Scan, And WiFi Connection to Hotspots. If you have ever worked with WifiManager you should know how painful it is to make a simple wifi network scan or even worse to connect to a hotspot programmatically. So that's what my new library is all about. To make it easier for me and hopefully for other developers as well to do those kind of tasks from Java code. So lets jump right in some code examples.

Enabling/Disabling WiFi

turn on device's wifi using the following:

 WifiUtils.withContext(getApplicationContext()).enableWifi(this::checkResult);

Where checkResult could be a custom-defined method of your own that would deal accordingly in each situation. For Example:

  private void checkResult(boolean isSuccess)
  {

if (isSuccess)

 Toast.makeText(MainActivity.this, "WIFI ENABLED", Toast.LENGTH_SHORT).show();

else

 Toast.makeText(MainActivity.this, "COULDN'T ENABLE WIFI", Toast.LENGTH_SHORT).show();

  
}

If you don't want to deal with call backs you can just pass null to enableWifi method like so.

 WifiUtils.withContext(getApplicationContext()).enableWifi(null);

Similarly you can turn off the wifi using this:

WifiUtils.withContext(getApplicationContext()).disableWifi();

Scanning for WiFi Networks

You can easily perform a WiFi Network scan like so:

WifiUtils.withContext(getApplicationContext()).scanWifi(this::getScanResults).start();
  private void getScanResults(@NonNull final List<ScanResult> results)  {

  if (results.isEmpty())
  {

Log.i(TAG, "SCAN RESULTS IT'S EMPTY");

return;
  
}

  Log.i(TAG, "GOT SCAN RESULTS " + results);
  
}

Connecting to WiFi Networks

Now lets get to the interesting stuff. You can connect to any WiFi network programmatically knowing only SSID and WPA/WPA2 key:

WifiUtils.withContext(getApplicationContext())

 .connectWith("MitsarasWiFi", "MitsarasPassword123")

 .onConnectionResult(this::checkResult)

 .start();

Again checkResult could be something like:

  private void checkResult(boolean isSuccess)
  {

if (isSuccess)

 Toast.makeText(MainActivity.this, "CONNECTED YAY", Toast.LENGTH_SHORT).show();

else

 Toast.makeText(MainActivity.this, "COULDN'T CONNECT", Toast.LENGTH_SHORT).show();

  
}

There are also a few other options that would allow you to do the same job: For example you can connect using SSID, BSSID and WPA/WPA2 Key:

 WifiUtils.withContext(getApplicationContext())

  .connectWith("MitsarasWiFi", "AB:CD:EF:12:34:56", "MitsarasPassword123")

  .onConnectionResult(this::checkResult)

  .start();

Lastly WifiUtils can also connect using a specified scanResult after a WiFi Scan is complete, for example:

WifiUtils.withContext(getApplicationContext())

 .connectWithScanResult("MitsarasPasword123", scanResults -> scanResults.get(0))

 .onConnectionResult(this::checkResult)

 .start();

The above example will perform a WiFi Scan and connectWithScanResult will return a List<ScanResult> scanResults with all the available WiFi networks around. The method then expects you to Return a single scanResult out of the list of results of your choice so that it can try to connect to it. The rest is pretty much the same.

Canceling an ongoing connection

You have two options to cancel a connection in progress.

  • If Connection takes too long to complete and just hangs in there without calling back onConnectionResult You can specify a TimeOut in milliseconds.
WifiUtils.withContext(getApplicationContext())

 .connectWith("MitsarasWiFi", "MitsarasPassword123")

 .setTimeout(15000)

 .onConnectionResult(this::checkResult)

 .start();

The Connection will fail in 15 seconds. The default timeOut is 30 seconds.

  • You can also cancel an ongoing connection immediately using the following:
 WifiConnectorBuilder.WifiUtilsBuilder builder = WifiUtils.withContext(getApplicationContext());
  builder.connectWith("MitsarasWiFi", "MitsarasPassword123")  .onConnectionResult(this::checkResult)  .start();
  builder.cancelAutoConnect();

Connecting with WPS keys.

On Androids 5.0 and greater there is also an option to connect using WPS keys. This library makes it easier and safer to connect using WPS than the stock android API.

WifiUtils.withContext(getApplicationContext())

 .connectWithWps("d8:74:95:e6:f5:f8", "51362485")

 .onConnectionWpsResult(this::checkResult)

 .start();

Enable Logging

If you want to receive some extra logging info comming from WiFi Utils you can enable its logging capabilities with WifiUtils.enableLog(true);

Permissions

Damn You are required to set a few permissions in order for this lib to work correctly :(

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> <!-- for Android 6 and above --> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> <!-- for Android 6 and above -->

Add it to your project

Add the following to your app module build.gradle file

 dependencies {

  compile 'com.thanosfisherman.wifiutils:wifiutils:<latest version here>'
  
}

Apps using this library

My app of course GWPA Finder Duh :P


Contributing?

There are a few more things left to be covered in this tutorial. Hopefully I will improve upon this in the future.

Feel free to add/correct/fix something to this library, I will be glad to improve it with your help.

License

Copyright 2017 Thanos Psaridis  Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License. You may obtain a copy of the License at
  http://www.apache.org/licenses/LICENSE-2.0  Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. 

Resources

A command-line tool to copy Android Material Design icons to your project folders: drawable-ldpi, drawable-mdpi, and etc.

Unofficial client for local Youtube alternative website.

RecyclerView Animators is an Android library that allows developers to easily create RecyclerView with animations.

Read incoming and outgoing text messages using an Android application across different Android SDK versions it's not trivial. If yo don't want to appear as SMS application and your application has to read incoming and outgoing SMSs this is your library.

This Android library offers you two main classes to use to start listening text messages. SMS Radar is implemented in top of an Android service. To start / stop listening text messages use SmsRadar.initializeSmsRadarService(context, listener) with a Context instance and a SmsListener implementation.

Fast JSON Processor.

android-asyncservice manages threading and caching transparently in your Android app.

It's an alternative to AsyncTasks, Loaders, or more advanced libs like RxJava, Robospice, Groundy, … but AsyncService focuses on keeping your code short and simple!

Topics


2D Engines   3D Engines   9-Patch   Action Bars   Activities   ADB   Advertisements   Analytics   Animations   ANR   AOP   API   APK   APT   Architecture   Audio   Autocomplete   Background Processing   Backward Compatibility   Badges   Bar Codes   Benchmarking   Bitmaps   Bluetooth   Blur Effects   Bread Crumbs   BRMS   Browser Extensions   Build Systems   Bundles   Buttons   Caching   Camera   Canvas   Cards   Carousels   Changelog   Checkboxes   Cloud Storages   Color Analysis   Color Pickers   Colors   Comet/Push   Compass Sensors   Conferences   Content Providers   Continuous Integration   Crash Reports   Credit Cards   Credits   CSV   Curl/Flip   Data Binding   Data Generators   Data Structures   Database   Database Browsers   Date &   Debugging   Decompilers   Deep Links   Dependency Injections   Design   Design Patterns   Dex   Dialogs   Distributed Computing   Distribution Platforms   Download Managers   Drawables   Emoji   Emulators   EPUB   Equalizers &   Event Buses   Exception Handling   Face Recognition   Feedback &   File System   File/Directory   Fingerprint   Floating Action   Fonts   Forms   Fragments   FRP   FSM   Functional Programming   Gamepads   Games   Geocaching   Gestures   GIF   Glow Pad   Gradle Plugins   Graphics   Grid Views   Highlighting   HTML   HTTP Mocking   Icons   IDE   IDE Plugins   Image Croppers   Image Loaders   Image Pickers   Image Processing   Image Views   Instrumentation   Intents   Job Schedulers   JSON   Keyboard   Kotlin   Layouts   Library Demos   List View   List Views   Localization   Location   Lock Patterns   Logcat   Logging   Mails   Maps   Markdown   Mathematics   Maven Plugins   MBaaS   Media   Menus   Messaging   MIME   Mobile Web   Native Image   Navigation   NDK   Networking   NFC   NoSQL   Number Pickers   OAuth   Object Mocking   OCR Engines   OpenGL   ORM   Other Pickers   Parallax List   Parcelables   Particle Systems   Password Inputs   PDF   Permissions   Physics Engines   Platforms   Plugin Frameworks   Preferences   Progress Indicators   ProGuard   Properties   Protocol Buffer   Pull To   Purchases   Push/Pull   QR Codes   Quick Return   Radio Buttons   Range Bars   Ratings   Recycler Views   Resources   REST   Ripple Effects   RSS   Screenshots   Scripting   Scroll Views   SDK   Search Inputs   Security   Sensors   Services   Showcase Views   Signatures   Sliding Panels   Snackbars   SOAP   Social Networks   Spannable   Spinners   Splash Screens   SSH   Static Analysis   Status Bars   Styling   SVG   System   Tags   Task Managers   TDD &   Template Engines   Testing   Testing Tools   Text Formatting   Text Views   Text Watchers   Text-to   Toasts   Toolkits For   Tools   Tooltips   Trainings   TV   Twitter   Updaters   USB   User Stories   Utils   Validation   Video   View Adapters   View Pagers   Views   Watch Face   Wearable Data   Wearables   Weather   Web Tools   Web Views   WebRTC   WebSockets   Wheel Widgets   Wi-Fi   Widgets   Windows   Wizards   XML   XMPP   YAML   ZIP Codes