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
Linda HamiltonOriginal
2024-11-07 10:08:02733browse

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 ) {
  // ...
}

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);

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"/> 

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!

Statement:
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