Problems with internet scanning method on Android

Asked

Viewed 38 times

0

I have this method to check if the device is connected. However I am getting some msgs of problems with synchronization of my data. And I’m thinking it must have been this alteration in the Internet verification method. I am not experienced, so I preferred to ask if there is something wrong or missing in this method. Thank you.

public static boolean isNetworkAvailable (Context context) {

        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected() && activeNetworkInfo.isAvailable();

}

2 answers

0


I usually use these two methods to ensure that it is connected to a network and that this network has internet.

public static boolean isOnline(Context context) {

    ConnectivityManager cm =
            (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if( netInfo != null && netInfo.isConnectedOrConnecting()){
        Log.d("Utils","Esta conectado em um rede!");
        if( isInternetAvailable()){
            Log.d("Utils","Possui internet na rede!");
            return true;
        }else{
            Log.e("Utils","Não possui internet na rede!");
        }
    }
    Log.e("Utils","Não está conectado na rede!");
    return false;
}

public static boolean isInternetAvailable() {
    try {
        InetAddress ipAddr = InetAddress.getByName("google.com");
        return !ipAddr.equals("");

    } catch (Exception e) {
        return false;
    }

}
  • I’ll test with some things you sent, to see if it solves the problem. Thank you.

0

Speak there ;)

This method returns you a boolean telling you whether or not you have internet on smart.

I hope it helps.


public boolean checkOnlineState() {
        ConnectivityManager CManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo NInfo = CManager.getActiveNetworkInfo();
        if (NInfo != null && NInfo.isConnectedOrConnecting()) {
            return true;
        }
        return false;
    }

if(checkOnlineState()){
   // tem internet
}else{
   // nao tem internet             
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.