WifiManager in Android
Last Updated :
23 Dec, 2021
WifiManager is the class related to the operations done with wifi. This class provides the primary API for managing all aspects of Wi-Fi connectivity. It deals with several categories of items:
- The list of available configured networks. The list can be viewed and updated, and attributes of individual entries can be modified.
- The currently active Wi-Fi network, if any. Connectivity can be established or torn down, and dynamic information about the state of the network can be queried.
- Results of access point scans, containing enough information to make decisions about what access point to connect to.
- It defines the names of various Intent actions that are broadcast upon any sort of the change in the Wi-Fi state.
Wifi of the android can be switched on manually or via the app. This article is all about making the app turn on the wifi without the user’s intervention.
Step by Step Implementation
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Working with the activity_main.xml file
There is no need to change anything inside the activity_main.xml file.
Step 3: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
public class MainActivity extends AppCompatActivity
{
private WifiManager wifiManager;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super .onCreate(savedInstanceState);
setContentView(R.layout.empty);
wifiManager=(WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
wifiManager.setWifiEnabled( true );
try
{
String ip=Formatter.formatIpAddress(wifiManager.getConnectionInfo().getIpAddress());
Toast.makeText(getApplicationContext(), "SUCCESSFULLY CONNECTED TO " +ip,Toast.LENGTH_SHORT).show();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
|
Output:
Share your thoughts in the comments
Please Login to comment...