I don\'t want my user to even try downloading something unless they have Wi-Fi connected. However, I can only seem to be able to tell if Wi-Fi is enabled, but they could sti
The following code (in Kotlin) works from API 21 until at least current API version (API 29). The function getWifiState() returns one of 3 possible values for the WiFi network state: Disable, EnabledNotConnected and Connected that were defined in an enum class. This allows to take more granular decisions like informing the user to enable WiFi or, if already enabled, to connect to one of the available networks. But if all that is needed is a boolean indicating if the WiFi interface is connected to a network, then the other function isWifiConnected() will give you that. It uses the previous one and compares the result to Connected.
It's inspired in some of the previous answers but trying to solve the problems introduced by the evolution of Android API's or the slowly increasing availability of IP V6. The trick was to use:
wifiManager.connectionInfo.bssid != null
instead of:
According to the documentation: https://developer.android.com/reference/kotlin/android/net/wifi/WifiInfo.html#getbssid it will return null if not connected to a network. And even if we do not have permission to get the real value, it will still return something other than null if we are connected.
Also have the following in mind:
On releases before android.os.Build.VERSION_CODES#N, this object should only be obtained from an Context#getApplicationContext(), and not from any other derived context to avoid memory leaks within the calling process.
In the Manifest, do not forget to add:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
Proposed code is:
class MyViewModel(application: Application) : AndroidViewModel(application) {
// Get application context
private val myAppContext: Context = getApplication<Application>().applicationContext
// Define the different possible states for the WiFi Connection
internal enum class WifiState {
Disabled, // WiFi is not enabled
EnabledNotConnected, // WiFi is enabled but we are not connected to any WiFi network
Connected, // Connected to a WiFi network
}
// Get the current state of the WiFi network
private fun getWifiState() : WifiState {
val wifiManager : WifiManager = myAppContext.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
return if (wifiManager.isWifiEnabled) {
if (wifiManager.connectionInfo.bssid != null)
WifiState.Connected
else
WifiState.EnabledNotConnected
} else {
WifiState.Disabled
}
}
// Returns true if we are connected to a WiFi network
private fun isWiFiConnected() : Boolean {
return (getWifiState() == WifiState.Connected)
}
}
I am using this in my apps to check if the active network is Wi-Fi:
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni != null && ni.getType() == ConnectivityManager.TYPE_WIFI)
{
// Do your work here
}
Many of answers use deprecated code, or code available on higer API versions. Now I use something like this
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if(connectivityManager != null) {
for (Network net : connectivityManager.getAllNetworks()) {
NetworkCapabilities nc = connectivityManager.getNetworkCapabilities(net);
if (nc != null && nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
&& nc.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET))
return true;
}
}
return false;
You can turn WIFI on if it's not activated as the following 1. check WIFI state as answered by @Jason Knight 2. if not activated, activate it don't forget to add WIFI permission in the manifest file
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Your Java class should be like that
public class TestApp extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//check WIFI activation
ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (mWifi.isConnected() == false) {
showWIFIDisabledAlertToUser();
}
else {
Toast.makeText(this, "WIFI is Enabled in your devide", Toast.LENGTH_SHORT).show();
}
}
private void showWIFIDisabledAlertToUser(){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("WIFI is disabled in your device. Would you like to enable it?")
.setCancelable(false)
.setPositiveButton("Goto Settings Page To Enable WIFI",
new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
Intent callGPSSettingIntent = new Intent(
Settings.ACTION_WIFI_SETTINGS);
startActivity(callGPSSettingIntent);
}
});
alertDialogBuilder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
dialog.cancel();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
}