I want to know how to create a method that when detect there is not any connection to internet in the mobile and then the method try to connect with a server every 5 seconds, please if you can put a example to how implement with retrofit it i will appreciated!, thanks!
-
Possible duplicate of [How to check internet access on Android? InetAddress never times out](http://stackoverflow.com/questions/1560788/how-to-check-internet-access-on-android-inetaddress-never-times-out) – ישו אוהב אותך Oct 06 '16 at 04:42
6 Answers
May be this code help you.
ConnectivityManager conMgr = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() != null
&& conMgr.getActiveNetworkInfo().isAvailable()
&& conMgr.getActiveNetworkInfo().isConnected()) {
Toast.makeText(context, "Internet Available", Toast.LENGTH_SHORT).show();
return true;
} else {
if (isShowAlert) {
Toast.makeText(context,
"NOT Internet Connection",
Toast.LENGTH_SHORT).show();
}
return false;
}

- 77
- 6
-
This only check if a device connected to a connection, but don't check if the internet is on or off. – ישו אוהב אותך Oct 06 '16 at 04:44
-
you need to call continuous this method when you call web service or something. – Priyank Virani Oct 06 '16 at 05:05
public static boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) yourContext
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager
.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
Check
if(isNetworkAvailable()){
// connected to internet
}else{
// not connected
}

- 2,173
- 15
- 26
-
This only check if a device connected to a connection, but don't check if the internet is on or off. – ישו אוהב אותך Oct 06 '16 at 04:44
this might be helpfull,
int intervalTime = 5000; // 5 sec
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
internetConnection();
}
}, intervalTime);
public class InternetConnection {
/** CHECK WHETHER INTERNET CONNECTION IS AVAILABLE OR NOT */
public static boolean checkConnection(Context context) {
final ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connMgr.getActiveNetworkInfo();
if (activeNetworkInfo != null) { // connected to the internet
Toast.makeText(context, activeNetworkInfo.getTypeName(), Toast.LENGTH_SHORT).show();
if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
// connected to wifi
return true;
} else if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
// connected to the mobile provider's data plan
return true;
}
}
return false;
}
}

- 90
- 9
-
This only check if a device connected to a connection, but don't check if the internet is on or off. – ישו אוהב אותך Oct 06 '16 at 04:44
There is no need to check every time. Define a Connectivity Change broadcast listener in your manifest and project and check connection just when the connectivity changes ( The code provided to you by @Priyank Virani )
There are some special cases which you should handle. some times the wifi is on and you are connected to a local wifi. You need to enter a password to use internet.(like libraries,airports , etc ...) in this situations the above code return true as internet is connected but in reality its false !!!! You should check it either with calling a webService you provided or by calling an api from a famous service in net.
Calling network related things every 5 seconds, prevent device from sleeping and have a very bad effect on battery of device

- 5,089
- 2
- 35
- 50
Previously I use one of these methods from How to check internet access on Android? InetAddress never times out:
public static int isInternetActiveWithPing() {
try {
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
int exitValue = process.waitFor();
return exitValue;
} catch (Exception ex) {
return -1;
}
}
public static boolean isInternetActiveWithInetAddress() {
try {
InetAddress inetAddress = InetAddress.getByName("www.google.com");
return inetAddress != null && !inetAddress.toString().equals("");
} catch (Exception ex) {
return false;
}
}
But it has a major drawback, which we need to always check if the internet is off or not.
The best way is using NetworkEvents. This library listening network connection state and change of the WiFi signal strength with Event Bus which also check if there is the internet connected or not.
By using NetworkEvents, you don't need to recheck internet connection every 5 seconds.

- 1
- 1

- 28,609
- 11
- 78
- 96
-
Thanks! well i was trying with networkEvent to disconnect the internet from my wifi but does not detected that there is not internet, just when i turn off the wifi is that the "OnEvent" method is called, you know how to solved it? – Raxor Oct 06 '16 at 21:39
-
Have you enable internet checking with something like: `networkEvents = new NetworkEvents(context, busWrapper) .enableInternetCheck();`? – ישו אוהב אותך Oct 07 '16 at 02:04
-
yes , i did this networkEvents = new NetworkEvents(getApplicationContext(), busWrapper).enableInternetCheck().setPingParameters("www.google.com",80,3000); but with this tell me when i connect to a wifi if there internet or not but is the internet state change , the functino doesnt tell me – Raxor Oct 08 '16 at 21:01
-
Have you define the Event Listener and catch the respected change with `@Subscribe public void onEvent(ConnectivityChanged event) { // get connectivity status from event.getConnectivityStatus() if(event.getConnectivityStatus() == ConnectivityStatus.WIFI_CONNECTED_HAS_INTERNET) { // is connected to internet} else if (event.getConnectivityStatus() == WIFI_CONNECTED_HAS_NO_INTERNET) { // no internet connection} }` ? – ישו אוהב אותך Oct 08 '16 at 23:58
Create a handle that runs in erver 5 sec
Handler myHandler = new Handler();
myRunnable = new Runnable() {
@Override
public void run() {
if(isNetWorkAvailable(getActivity()))
{
webService();
}
else
{
//NO NETWORK
}
}
};
myHandler.postDelayed(myRunnable, 5000);// runs in ever 5 sec
private void webservice() {
// create 2 getters and setters java classes ie..LoginRequest & LoginResponse
LoginRequest loginRequest = new LoginRequest(userEmail, userPassword);
final ProgressDialog progressDialog = new ProgressDialog(mContext);
progressDialog.setTitle("Please Wait");
progressDialog.show();
Call<LoginResponse> call = GApiClient.get().postWithFormParams(loginRequest);
call.enqueue(new Callback<LoginResponse>() {
@Override
public void onResponse(Response<LoginResponse> response) {
progressDialog.dismiss();
Log.i("Response ", "Present");
}
@Override
public void onFailure(Throwable t) {
progressDialog.dismiss();
RetrofitError retrofitError;
if (e instanceof RetrofitError) {
retrofitError = ((RetrofitError) e);
if (retrofitError.getKind() == RetrofitError.Kind.NETWORK) {
return "Network is down!";
}
}
Log.i("Response ", " error");
}
});
}
public static int getConnectivityStatus(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (null != activeNetwork) {
return TYPE_WIFI;
}
return TYPE_NOT_CONNECTED;
}
public static boolean isNetWorkAvailable(Context context) {
int status = getConnectivityStatus(context);
if (status != 0) {
return true;
} else {
return false;
}
}
Apiclient class for retrofit 2.2
public class GApiClient {
private static GServiceApi REST_CLIENT;
public static final String API_URL = "YOUR BASE URL";
static {
setupRestClient();
}
private ApiClient() {
}
public static ServiceApi get() {
return REST_CLIENT;
}
private static void setupRestClient() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(API_URL_TEST)
.addConverterFactory(GsonConverterFactory.create())
.build();
REST_CLIENT = retrofit.create(GServiceApi.class);
}
}
Create a interface ServiceApi
public interface ServiceApi {
@POST("/verify/json") //rest of url
Call<Employee> postWithFormParams(@Body UserDetails data);
}

- 13,173
- 5
- 29
- 38
-
Goodin retrofit part. Code only checks if a device connected to a connection, but don't check if the internet is on or off. – ישו אוהב אותך Oct 06 '16 at 04:46
-
not getting ur scenario... above code checks if there is a internet connection – Rissmon Suresh Oct 06 '16 at 04:49
-
You can try by connecting your device to a WiFi Access point which not connected to the internet. Or trying using a local network. – ישו אוהב אותך Oct 06 '16 at 04:52
-
ok i understand.You can check that only by communcation timeout occurs and the call to retrofit onFailure occurs – Rissmon Suresh Oct 06 '16 at 04:59