0

I was looking at the post:

Detect if Android device has Internet connection

and method for checking internet connection works fine, only thing that is bothering me is that i have to check that in background thread (cant check from the main thread)

what i need is to check if there is internet connection, and after i get answer i need to continue from that line of the code.

Problem is that if i check for connection in background thred (AsyncTask), main thred will make new thread and continue with compiling rest of the code.

Here is my code:

if(dbAdapter.doesDbExist(this)){
        Log.e("Da li baza postoji", "postoji");
        if(hasActiveInternetConnection(this)){
            new DownloadAllProizvodiTask(1).execute();
        }
    }
    else {
        Log.e("Da li baza postoji", "ne postoji");
        if(hasActiveInternetConnection(this)){
            new DownloadAllProizvodiTask(2).execute();
        }
        else{
            Toast.makeText(this, "U need internet connection to download resorces", Toast.LENGTH_LONG);
            finish();
        }
    }

So i have to put method hasActiveInternetConnection() into asynctask, and when it finish, it has to continue from that if.

could someone give me some suggestions how to do that?

Community
  • 1
  • 1
toskebre
  • 385
  • 2
  • 7
  • 18

1 Answers1

1

You just have to rework the ordering of things to get it working with an AsyncTask. Your AsyncTask should look something like this:

new AsycTask<Void, Void, Boolean>() {
  @Override Boolean doInBackground(Void... params) {
    return hasActiveInternetConnection(...);
  }

  @Override onPostExecute(Boolean result) {
    if(result) {
      new DownloadAllProizvodiTask(2).execute();
    } else {
      Toast.makeText(this, "U need internet connection to download resorces", Toast.LENGTH_LONG);
      finish();
    }
  }
}.execute();

In your outer else, just start this task instead.

Andy Gaskell
  • 31,495
  • 6
  • 74
  • 83