简体   繁体   English

检查设备是否可以连接互联网,然后继续输入代码

[英]Check if device has internet connection and then continue with code

I was looking at the post: 我在看帖子:

Detect if Android device has Internet connection 检测Android设备是否可以连接互联网

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. 问题是,如果我在后台thred(AsyncTask)中检查连接,则main thred将创建新线程并继续编译其余代码。

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. 因此,我必须将hasActiveInternetConnection()方法放入asynctask中,并在完成时从if继续执行。

could someone give me some suggestions how to do that? 有人可以给我一些建议吗?

You just have to rework the ordering of things to get it working with an AsyncTask. 您只需对事物的顺序进行重新整理,即可使其与AsyncTask一起使用。 Your AsyncTask should look something like this: 您的AsyncTask应该看起来像这样:

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. 在您的外部,只需开始执行此任务即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM