Home > Java > javaTutorial > How Can I Control Wi-Fi and Internet Connectivity in Android Programmatically?

How Can I Control Wi-Fi and Internet Connectivity in Android Programmatically?

Linda Hamilton
Release: 2024-11-07 10:08:02
Original
731 people have browsed it

How Can I Control Wi-Fi and Internet Connectivity in Android Programmatically?

How to Control Wi-Fi and Internet Connectivity in Android Programmatically

The Connectivity Manager class allows us to access the device's network connectivity information. To determine if the device is connected to a network, we can use the following code:

ConnectivityManager connec = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);

// ARE WE CONNECTED TO THE NET
if ( connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED ||
  connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED ) {
  // ...
}
Copy after login

However, this method does not allow us to switch between network connections or disable them programmatically.

Enabling or Disabling Wi-Fi

To control Wi-Fi connectivity, we can use the WifiManager class:

WifiManager wifiManager = (WifiManager)this.context.getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(status);
Copy after login

where status is either true to enable Wi-Fi or false to disable it.

Required Permissions

The following permissions are required in the manifest file:

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/> 
Copy after login

Note: Disabling Wi-Fi or Internet connectivity may affect the functionality of other applications on the device. It is important to consider this before making any changes.

The above is the detailed content of How Can I Control Wi-Fi and Internet Connectivity in Android Programmatically?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template