I want to check Internet connection throughout the run time of my Android application. I tried using services but seems like it is not the best option. Is there any possible
You need not to use Service or BroadCastReceiver for this purpose. Just check Connection status everyTime you need to ping the server.
you can write a method which checks this and returns a boolean(true/false) according to connection status.
Below method does the same.
public static boolean isNetworkAvailable(Context mContext) {
try {
final ConnectivityManager conn_manager = (ConnectivityManager) mContext
.getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo network_info = conn_manager
.getActiveNetworkInfo();
if (network_info != null && network_info.isConnected()) {
if (network_info.getType() == ConnectivityManager.TYPE_WIFI)
return true;
else if (network_info.getType() == ConnectivityManager.TYPE_MOBILE)
return true;
}
} catch (Exception e) {
// TODO: handle exception
}
return false;
}