0

I'm trying to implement Internet check in Android in AsyncTask. I've created a separate class file for this. The aim is to check Internet in doInBackground and return the value to onPostExecute -and show the result in main UI thread. But what must be the context argument for isNetworkAvailable(context)? For now it gives error about argument. Also is it all OK with isNetworkAvailable?

How to use this value in onPostExecute and pass it to the main UI thread?

import android.content.Context;
import android.net.ConnectivityManager;
import android.os.AsyncTask; 

class InternetCheck extends AsyncTask<Void, Void, Boolean> {


        protected Boolean doInBackground(Void... noargs) {

            return isNetworkAvailable(this);

        }

        protected void onProgressUpdate(Integer... progress) {

         }


        protected void onPostExecute(String result) {

        }

        public static boolean isNetworkAvailable(Context context) 
        {
            return ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo() != null;
        }
}
user2543953
  • 123
  • 1
  • 3
  • 11

3 Answers3

4

Pass your Activity/Fragement as context. As an very very simple example:

class InternetCheck extends AsyncTask<Activity, Void, Boolean> {


        protected Boolean doInBackground(Activity... activitys) {

            return isNetworkAvailable(activitys[0]);

        }

        protected void onProgressUpdate(Integer... progress) {

         }


        protected void onPostExecute(String result) {

        }

        public static boolean isNetworkAvailable(Context context) 
        {
            return ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo() != null;
        }
}

As a side note: I'm not sure that getting network info does need that much time to do it in the background.

Patrick
  • 33,984
  • 10
  • 106
  • 126
2

No need to do an AsyncTask for this:

/** This method check internet connection. True for connection enabled, false otherwise. */
public boolean isOnline() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        return true;
    }
    return false;
}

For everything you do with network don't forget permission.

JJ86
  • 5,055
  • 2
  • 35
  • 64
  • As I saw, in Android 4.0+ Net calls must be in a separate thread. Is it true? – user2543953 Jul 06 '13 at 13:37
  • 1
    @user2543953 you are not making any network related operation. You are only checking for network connection availaiblity. – Raghunandan Jul 06 '13 at 13:39
  • @user2543953 i'm using it on my published project ;) . – JJ86 Jul 06 '13 at 13:40
  • Maybe I'll check also with isReachable function, checking the given server. It's all the same in this way? – user2543953 Jul 06 '13 at 13:45
  • @user2543953 sincerely i never used it, you can try this method and make your own conclusion; in any case read this http://stackoverflow.com/questions/9922543/why-does-inetaddress-isreachable-return-false-when-i-can-ping-the-ip-address – JJ86 Jul 06 '13 at 13:49
  • Yes, I saw it; it's possible to check for HTTP 200 status, for example. – user2543953 Jul 06 '13 at 13:59
  • @user2543953 cool, if anyone helped you, accept his/her answer; or you can insert your own answer and accept it! – JJ86 Jul 06 '13 at 14:04
  • And is there any example of checking connection for 200 status with exceptions handling? Or ping is better? – user2543953 Jul 06 '13 at 14:14
  • @user2543953 i simple research brought me here http://stackoverflow.com/questions/14576710/ping-application-in-android/ – JJ86 Jul 06 '13 at 14:19
1

You need Activity context

  ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();

In your case this does not refer to activity context.

     protected Boolean doInBackground(Void... noargs) {

        return isNetworkAvailable(this);
    }

I am not sure if the below posted code is the best way. You can check if connection is available and then do some task.

public class NetworkHelper {
private static final String TAG=NetworkHelper.class.getSimpleName();

public static boolean isInternetAvailable(Context context)
{
    NetworkInfo info = (NetworkInfo) ((ConnectivityManager)
    context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();

    if (info == null)
    {
         Log.d(TAG,"No Network connection");
         return false;
    }
    else
    {
        if(info.isConnected())
        {
            Log.d(TAG," Network connection available...");
            return true;
        }
        else
        {
            Log.d(TAG,"no Network connection");
            return false;
        }

    }
}
}

In your activity class

  if(NetworkHelper.isInternetAvailable(ActivityName.this))
  {
        // do some task
  }  
  else
  {
        Toast.makeText(ActivityName.this,"No Network connection available",1000).show();
  } 

Note : This checks for network availability. You may be conencted to a wifi but your wifi may be connected to the net.

Raghunandan
  • 132,755
  • 26
  • 225
  • 256
  • Thanks. What about Internet Check, it's a separate function, but how to do it's in an AsyncTask starting from the UI thread, it's a question... – user2543953 Jul 06 '13 at 13:39
  • if you need to something in asynctask that requires network connection. check the availability before you invoke the asycntask. – Raghunandan Jul 06 '13 at 13:41
  • I thought to do this in the asynctask just. – user2543953 Jul 06 '13 at 13:44
  • So how to pass the context here, is it right `code`class InternetCheck extends AsyncTask { protected Boolean doInBackground(Activity activity) { return isNetworkAvailable(???); } `/code` – user2543953 Jul 06 '13 at 13:49
  • @user2543953 why do you need a asynctask in the first place? i suggest you read the asynctask docs first. – Raghunandan Jul 06 '13 at 13:52
  • Because I'm going to check the connection and check the connection to the given server in the Net. Also maybe I'll use AsyncTask later for other purposes. – user2543953 Jul 06 '13 at 13:56
  • @user2543953 to check for network connection availability you don't need asynctask. – Raghunandan Jul 06 '13 at 13:56
  • But when I add to my Internet check function the request to the given server on the Web, it will require new thread at least for Android 4.0+. So I'm to use it. – user2543953 Jul 06 '13 at 14:00
  • read my previous comment's you can check for network availability before and then invoke your asynctask. I think you are getting confused. Say you need to make http post request. you will do in asynctask. so check network availability in activity class. if available invoke asynctask else display a toast to the user – Raghunandan Jul 06 '13 at 14:01