How can I check internet connection in Android Q? - java

Before Android Q all you had to do is use the NetworkUtils class. But this class was deprecated in API 29.
I've been searching for an alternative, and I couldn't seem to find one.
So, how can I check the internet connection in Android Q?

Use this code snippet.
#IntRange(from = 0, to = 3)
public static int getConnectionType(Context context) {
int result = 0; // Returns connection type. 0: none; 1: mobile data; 2: wifi
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (cm != null) {
NetworkCapabilities capabilities = cm.getNetworkCapabilities(cm.getActiveNetwork());
if (capabilities != null) {
if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
result = 2;
} else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
result = 1;
} else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN)) {
result = 3;
}
}
}
} else {
if (cm != null) {
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null) {
// connected to the internet
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
result = 2;
} else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
result = 1;
} else if (activeNetwork.getType() == ConnectivityManager.TYPE_VPN) {
result = 3;
}
}
}
}
return result;
}
Add the below permissions in AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />

If you are looking for a simple code, you can use this:
public static boolean isInternetConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return cm.getActiveNetwork() != null && cm.getNetworkCapabilities(cm.getActiveNetwork()) != null;
} else {
return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnectedOrConnecting();
}
}

The ConnectivityManager only checks whether the smartphone could theoretically establish an Internet connection. Whether an Internet connection actually exists, e.g. if the network quality is very poor, can only be determined with a ping or a web address.

Just use this code and call isInternatAvailable(context).
private static final String CMD_PING_GOOGLE = "ping -w -c 1 google.com";
public static boolean isInternetAvailable(#NonNull Context context) {
return isConnected(context) && checkInternetPingGoogle();
}
public static boolean isConnected(#NonNull Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if(cm != null) {
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
} else {
return false;
}
}
public static boolean checkInternetPingGoogle(){
try {
int a = Runtime.getRuntime().exec(CMD_PING_GOOGLE).waitFor();
return a == 0x0;
} catch (IOException ioE){
EMaxLogger.onException(TAG, ioE);
} catch (InterruptedException iE){
EMaxLogger.onException(TAG, iE);
}
return false;
}

Related

Check is Internet available - Should we check for NetworkCapabilities.TRANSPORT_BLUETOOTH, TRANSPORT_VPN, ... as well?

Previously, before API 28, we can use NetworkInfo, to check whether Internet is available without much effort. A single call on isConnectedOrConnecting will be sufficient enough.
private static boolean isInternetAvailable(Context context) {
ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm == null) {
// Will it happen ever?
return false;
}
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
But, quite a number of methods of NetworkInfo is deprecated. Hence, we need to modify our code to
private static boolean isInternetAvailable(Context context) {
ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm == null) {
// Will it happen ever?
return false;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
Network activeNetwork = cm.getActiveNetwork();
if (activeNetwork == null) {
return false;
}
NetworkCapabilities networkCapabilities = cm.getNetworkCapabilities(activeNetwork);
if (networkCapabilities != null) {
if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
return true;
} else if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
return true;
} else if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)){
return true;
}
}
return false;
} else {
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
}
We was wondering, should we perform check on the following remaining capabilities, to determine whether Internet is available?
TRANSPORT_BLUETOOTH
TRANSPORT_VPN
TRANSPORT_WIFI_AWARE
TRANSPORT_LOWPAN
As, it is difficult to have access to all kinds of network connection, and we do not have luxury to do all the cases testing.

How to use Connectivity manager.NetworkCallback to get network type

In my project I want to show the type of connection that is used.
For example when the user enables wifi and opens the app
The toast with WiFi enabled is shown if used mobile data then another toast should be shown.
I used the following code to show the type but I found that TYPE_WIFI & TYPE_MOBILE is deprecated and suggests to use the ConnectivityManager.NetworkCallback();. So I'm confused how to use it
Just help me know how to do that
Here is my code snippet
public void CheckConnection(){
ConnectivityManager manager = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = manager.getActiveNetworkInfo();
if(null!=activeNetwork){
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI){
Toast.makeText(this, "Connected with Wi-Fi", Toast.LENGTH_SHORT).show();
}
else if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE){
Toast.makeText(this, "Connected with Cellular Data", Toast.LENGTH_SHORT).show();
}
}
else {
Toast.makeText(this,"No Internet connection Detected",Toast.LENGTH_SHORT).show();
}
}
Try this out :
public class NetworkUtil {
public static int TYPE_WIFI = 1;
public static int TYPE_MOBILE = 2;
public static int TYPE_NOT_CONNECTED = 0;
public static int getConnectivityStatus(Context context) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (null != activeNetwork) {
if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
return TYPE_WIFI;
if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
return TYPE_MOBILE;
}
return TYPE_NOT_CONNECTED;
}
public static String getConnectivityStatusString(Context context) {
int conn = NetworkUtil.getConnectivityStatus(context);
String status = null;
if (conn == NetworkUtil.TYPE_WIFI) {
status = "Wifi enabled";
} else if (conn == NetworkUtil.TYPE_MOBILE) {
status = "Mobile data enabled";
} else if (conn == NetworkUtil.TYPE_NOT_CONNECTED) {
status = "Not connected to Internet";
}
return status;
}
}
Second create Broadcast receiver where you will get all this changes :
public class NetworkChangeReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, final Intent intent) {
String status = NetworkUtil.getConnectivityStatusString(context);
Toast.makeText(context, status, Toast.LENGTH_LONG).show();
}
}
And don't forgot to add your broadcast into mainfest :
<receiver
android:name="YOUR PACKAGE NAME"
android:label="NetworkChangeReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
</intent-filter>
</receiver>
Also alternative of getType() : in kotlin
private fun isInternetAvailable(context: Context): Boolean {
var result = false
val connectivityManager =
context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val networkCapabilities = connectivityManager.activeNetwork ?: return false
val actNw =
connectivityManager.getNetworkCapabilities(networkCapabilities) ?: return false
result = when {
actNw.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true
actNw.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true
actNw.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> true
else -> false
}
} else {
connectivityManager.run {
connectivityManager.activeNetworkInfo?.run {
result = when (type) {
ConnectivityManager.TYPE_WIFI -> true
ConnectivityManager.TYPE_MOBILE -> true
ConnectivityManager.TYPE_ETHERNET -> true
else -> false
}
}
}
}
return result
}
Alternative of getType() in java :
public static boolean isInternetAvailable(Context context) {
boolean result = false;
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (cm != null) {
NetworkCapabilities capabilities = cm.getNetworkCapabilities(cm.getActiveNetwork());
if (capabilities != null) {
if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
result = true;
} else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
result = true;
}
}
}
} else {
if (cm != null) {
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null) {
// connected to the internet
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
result = true;
} else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
result = true;
}
}
}
}
return result;
}

Import deprecated warning after updating target sdk to 29

After updating compile and targetSdkVersion to "29" in build.gradle I get deprecation warning:
warning: [deprecation] NetworkInfo in android.net has been deprecated
import android.net.NetworkInfo;
^
Build fails because of this. But I use Network info to have compatibility with api versions 16-29. How should I handle deprecated imports targeting api "29" and above?
I found the solution to this one. You must write the method in this way.
#SuppressWarnings("deprecation")
public boolean isConnected() {
ConnectivityManager cm = (ConnectivityManager) AnkiDroidApp.getInstance().getApplicationContext()
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm == null) {
return false;
}
/* NetworkInfo is deprecated in API 29 so we have to check separately for higher API Levels */
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
Network network = cm.getActiveNetwork();
if (network == null) {
return false;
}
NetworkCapabilities networkCapabilities = cm.getNetworkCapabilities(network);
if (networkCapabilities == null) {
return false;
}
boolean isInternetSuspended = !networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED);
return networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
&& networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
&& !isInternetSuspended;
} else {
android.net.NetworkInfo networkInfo = cm.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnected();
}
}
Remember to suppress warning.
The Answer of your question is in this Link!
NetworkCapabilities is not deprecated in API 29 but it requires API 21 so I have called it on API 29 only.
public static boolean isNetworkAvailable(Context context) {
if(context == null) return false;
ConnectivityManager connectivityManager = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null) {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
NetworkCapabilities capabilities =
connectivityManager.getNetworkCapabilities(connectivityManager.getActiveNetwork());
if (capabilities != null) {
if
(capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
return true;
} else if
(capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
return true;
} else if
(capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)){
return true;
}
}
}
else {
try {
NetworkInfo activeNetworkInfo =
connectivityManager.getActiveNetworkInfo();
if (activeNetworkInfo != null && activeNetworkInfo.isConnected()) {
Log.i("update_statut", "Network is available : true");
return true;
}
} catch (Exception e) {
Log.i("update_statut", "" + e.getMessage());
}
}
}
Log.i("update_statut","Network is available : FALSE ");
return false;
}

Check internet status from the main activity

I'm new student on android development, so I don't have the enough experience for coding, so I need the help from you...
I create a java class on android studio to check if there is an internet connection or not :
import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class InternetStatus {
private static final String LOG_TAG ="InternetStatus";
public static boolean hasActiveInternetConnection(Context context) {
if (isNetworkAvailable((Activity) context)) {
try {
HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1500);
urlc.connect();
return (urlc.getResponseCode() == 200);
} catch (IOException e) {
Log.e(LOG_TAG, "Error checking internet connection", e);
}
} else {
Log.d(LOG_TAG, "No network available!");
}
return false;
}
public static boolean isNetworkAvailable(Activity mActivity) {
Context context = mActivity.getApplicationContext();
ConnectivityManager connectivity = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) {
return false;
} else {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false;
}
}
So, I have two questions :
1- is this the right code or I'm missing something ?
2- as you see this is a java class, if I create a button on my main activity to check if there is an internet connection or not !! how I can do that by importing this class or something like that ?!!
// Check if there is any connectivity for a Wifi network
public boolean isConnectedWifi(){
NetworkInfo info = Connectivity.getNetworkInfo(Context);
return info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_WIFI;
}
// Check if there is any connectivity for a mobile network
public boolean isConnectedMobile(){
NetworkInfo info = Connectivity.getNetworkInfo(Context);
return info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_MOBILE;
}
// Check all connectivities whether available or not
public boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnected();
}
How to use?
For example, we need to check if the connectivity is available:
if(isNetworkAvailable()){
// do your thing here.
}
When the network is available, we need to check whether it is WiFi or Mobile network:
if(isConnectedWifi()){
// do your thing here with WiFi Network.
}
if(isConnectedMobile()){
// do your thing here with Mobile Network.
}
First of all, you must include a permission request in AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Then, create a method to check if internet connection is active:
public static boolean isInternetConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
}
In your MainActivity class
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_camera);
boolean isavailable = InternetStatus.hasActiveInternetConnection(getApplicationContext);
}
}
if you have a button
boolean isavailable ;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_camera);
Button someButton = (Button) findViewById(R.id.yourButton);
someButton.setOnClickListener(new onClickLIstener(){
isavailable = InternetStatus.hasActiveInternetConnection(getApplicationContext);
});
}
}
To check the connectivity status no need to connect to internet and get status code. Use below code.
public boolean isConnected() {
ConnectivityManager manager = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo info = manager.getActiveNetworkInfo();
if (info != null && info.isConnected()) {
return true;
} else {
return false;
}
}
Which will return true or false based on active network status.
On your button click simply call this function, If it returns true, there is a connection. If it returns false, there is no active internet connection.
Just Put info.isConnected() in your isNetworkAvailable function:
public static boolean isNetworkAvailable(Activity mActivity) {
...
if (connectivity == null) {
return false;
} else {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null && info.isConnected()) {
...
}
}
}
return false;
}
Most of the answers are outdated
fun isNetworkAvailable(context : Context): Boolean {
val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
if (isAndroidVersionAboveLollipop()) {
val activeNetwork = connectivityManager.activeNetwork ?: return false
val networkCapabilities = connectivityManager.getNetworkCapabilities(activeNetwork) ?: return false
networkCapabilities.let {
return it.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) && it.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
}
} else {
return connectivityManager.activeNetworkInfo?.isConnectedOrConnecting ?: false
}
}
fun isAndroidVersionAboveLollipop() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.M

Connection status - how to call method from another class

I wrote application which have to check status if internet connection and I would like to call this method in another class, but I don't know how should I do this.
Here is the code responsible for checking internet connection:
public class NetworkUtil {
public static int TYPE_WIFI = 1;
public static int TYPE_MOBILE = 2;
public static int TYPE_NOT_CONNECTED = 0;
public static int getConnectivityStatus(Context context) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (null != activeNetwork) {
if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
return TYPE_WIFI;
if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
return TYPE_MOBILE;
}
return TYPE_NOT_CONNECTED;
}
public static String getConnectivityStatusString(Context context) {
int conn = NetworkUtil.getConnectivityStatus(context);
String status = null;
if (conn == NetworkUtil.TYPE_WIFI) {
status = "Wifi enabled";
} else if (conn == NetworkUtil.TYPE_MOBILE) {
status = "Mobile data enabled";
} else if (conn == NetworkUtil.TYPE_NOT_CONNECTED) {
status = "Not connected to Internet";
}
return status;
}
}
and broadcast class:
public class NetworkChangeReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, final Intent intent) {
String status = NetworkUtil.getConnectivityStatusString(context);
Toast.makeText(context, status, Toast.LENGTH_LONG).show();
}
}
I would like to check in another class, or at the moment there is no connection (getConnectivityStatus return TYPE_NOT_CONNECTED) and execute some code like this:
if (connection is missing - i don't know what should i put in this place) {
// other code
}
else {
}
Can you help me?
Not sure what your problem is...
if (NetworkUtil.getConnectivityStatus(getApplicationContext()) == NetworkUtil.TYPE_NOT_CONNECTED) {
}else {
}
Hope it helps
if (NetworkUtil.getConnectivityStatus(getApplicationContext()) == NetworkUtil.TYPE_NOT_CONNECTED) {
//NOT CONNECTED!
}else {
//CONNECTED!
}
you can also change your method to retrieve a boolean value:
public static boolean getConnectivityStatus(Context context) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (null != activeNetwork) {
if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
return true;
if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
return true;
}
return false;
}
and your code will be like:
if (NetworkUtil.getConnectivityStatus(getApplicationContext())) {
//CONNECTED!
}else {
//NOT CONNECTED!
}
Note:
If you are inside a fragment you can call your method as:
NetworkUtil.getConnectivityStatus(getActivity().getApplicationContext())
here what I made:
First i register my receiver in my activity :
registerReceiver(
new NetworkChangeReceiver(),
new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)
);
here is my Receiver:
public class NetworkChangeReceiver extends BroadcastReceiver {
private static final String TAG = "NetworkStateReceiver";
#Override
public void onReceive(Context context, Intent intent) {
Log.v(TAG, "[status]: " + NetworkUtils.getConnectivityStatus(context));
}
}
and finally my NetworkUtils is as simple as this :
public enum NetworkStatus{
NETWORK_STATUS_NOT_CONNECTED,
NETWORK_STATUS_WIFI,
NETWORK_STATUS_MOBILE
}
public static NetworkStatus getConnectivityStatus(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (null != activeNetwork) {
if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
return NetworkStatus.NETWORK_STATUS_WIFI;
if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
return NetworkStatus.NETWORK_STATUS_MOBILE;
}
return NetworkStatus.NETWORK_STATUS_NOT_CONNECTED;
}
}

Categories

Resources