In this post, we will see how to check the Network Connectivity Status in Android. Our app may have to behave differently based on the network it is connected i.e wifi,mobile,vpn etc., To check the network connectivity info, we use the ConnectivityManager and NetworkInfo class of android net package.
The below snippet demonstrates how to detect whether the mobile is connected to WIFI or Mobile data.
The below snippet demonstrates how to detect whether the mobile is connected to WIFI or Mobile data.
Code Snippet:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package androidbite.blog; | |
import android.content.Context; | |
import android.net.ConnectivityManager; | |
import android.net.NetworkInfo; | |
import android.support.v7.app.AppCompatActivity; | |
import android.os.Bundle; | |
import android.widget.Toast; | |
public class NetworkStatusActivity extends AppCompatActivity { | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_network_status); | |
Toast.makeText(this, getConnectivityStatus(this), Toast.LENGTH_SHORT).show(); | |
} | |
private String getConnectivityStatus(Context context) { | |
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); | |
NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); | |
if (null != activeNetwork && activeNetwork.getState() == NetworkInfo.State.CONNECTED) { | |
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) return "WIFI"; | |
if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) return "MOBILE"; | |
} | |
return "NOT_CONNECTED"; | |
} | |
} |