views:

6974

answers:

5

I got a AsyncTask that is supposed to check the network access to a host name. But the doInBackground is never timed out. Anyone have a clue?

public class HostAvailabilityTask extends AsyncTask<String, Void, Boolean>{

private Main main;

public HostAvailabilityTask(Main main){
    this.main = main;
}

protected Boolean doInBackground(String... params) {
    Main.Log("doInBackground() isHostAvailable():"+params[0]);

    try {
        return InetAddress.getByName(params[0]).isReachable(30); 
    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return false;       
}

protected void onPostExecute(Boolean... result) {
    Main.Log("onPostExecute()");

    if(result[0] == false){
        main.setContentView(R.layout.splash);
        return;
    }

    main.continueAfterHostCheck();
}

}
+8  A: 

Take a look at the ConnectivityManager class. You can use this class to get information on the active connections on a host. http://developer.android.com/reference/android/net/ConnectivityManager.html

EDIT: You can use

Context.getSystemService(Context.CONNECTIVITY_SERVICE).getNetworkInfo(ConnectivityManager.TYPE_MOBILE)

or

Context.getSystemService(Context.CONNECTIVITY_SERVICE).getNetworkInfo(ConnectivityManager.TYPE_WIFI)

and parse the DetailedState enum of the returned NetworkInfo object

EDIT EDIT: To find out whether you can access a host, you can use

Context.getSystemService(Context.CONNECTIVITY_SERVICE).requestRouteToHost(TYPE_WIFI, int hostAddress)

Obviously, I'm using Context.getSystemService(Context.CONNECTIVITY_SERVICE) as a proxy to say

ConnectivityManager cm = Context.getSystemService(Context.CONNECTIVITY_SERVICE);
    cm.yourMethodCallHere();
Chinmay Kanchi
Not sure, but this seems like code to test what kind of network connection im currently on. E.g im on WiFi, there is no guarantee that you home wifi router is connected to internett... to check that you actually need to do a request to a internetserver...
PHP_Jedi
There was a mistake in the EDIT EDIT section, I'd left out the requestRouteToHost() call. Re-read the answer now :)
Chinmay Kanchi
A: 

Im using this code instead of the InetAddress :

 try {

  URL url = new URL("http://"+params[0]);

     HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
     urlc.setRequestProperty("User-Agent", "Android Application:"+Z.APP_VERSION);
     urlc.setRequestProperty("Connection", "close");
     urlc.setConnectTimeout(1000 * 30); // mTimeout is in seconds
  urlc.connect();
     if (urlc.getResponseCode() == 200) {
            Main.Log("getResponseCode == 200");
      return new Boolean(true);
     }
 } catch (MalformedURLException e1) {
  // TODO Auto-generated catch block
  e1.printStackTrace();
    } catch (IOException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 }
PHP_Jedi
+13  A: 

No need to be complex. The simplest and framework manner is to use ACCESS_NETWORK_STATE permission and just make a connected method

public boolean isOnline() {
 ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
 return cm.getActiveNetworkInfo().isConnectedOrConnecting();

}

You can also use requestROuteToHost if you have a particualr host and connection type (wifi/mobile) in mind.

Eddie
+2  A: 

Need also to add to the manifest the fallowing to get the getActiveNetworkInfo()

uses-permission android:name="android.permission.INTERNET"

uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"

Adrian

azelez
@azelez really supporting answer, i have done code but forgot to add 2nd permision in manifest file. but now it is solved.
PM - Paresh Mayani
A: 

@Eddie. Just a minor edit to your solution - if the device is in airplane mode (or presumably in other situations where there's no available network), cm.getActiveNetworkInfo() will be null, so you need to add a null check. Modified solution below:

public boolean isOnline() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        return true;
    }
    return false;
}

One other small point, if you absolutely need a network connection at the given point in time, then it might be better to use netInfo.isConnected() rather than netInfo.isConnectedOrConnecting. I guess this is up to the indivudal use-case however.

gar