Controlling Network Connectivity in Android
Introduction
Connecting to and disconnecting from Wi-Fi or the internet is a common task in Android programming. This article explores how to programmatically control network connectivity by enabling, disabling, or switching between networks.
Enable/Disable Wi-Fi
To enable or disable Wi-Fi, you must use the WifiManager class. Here's how:
WifiManager wifiManager = (WifiManager)this.context.getSystemService(Context.WIFI_SERVICE); wifiManager.setWifiEnabled(status);
where status can be true (to enable) or false (to disable).
Edit: Permissions
To use the WifiManager, you need to declare the following permissions in your Android Manifest file:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
Note: Changing Wi-Fi state requires additional permissions depending on the Android version.
Switching Networks
Unfortunately, the ConnectivityManager class does not provide a direct method to switch between networks. However, you can use a workaround by enabling the desired network and then disabling the other.
Conclusion
This article has demonstrated how to programmatically control Wi-Fi connectivity in Android. By using the WifiManager class, you can enable, disable, or switch between networks, providing greater flexibility in managing network connections in your applications.
The above is the detailed content of How to Programmatically Control Network Connectivity in Android?. For more information, please follow other related articles on the PHP Chinese website!