AsyncTask的返回一个布尔值?最好的方式来实现?最好的、来实现、方式、布尔值

2023-09-07 03:10:13 作者:社会复杂爷简单

我试图检查连接到Android手机上的互联网(一个实际的连接,而不是网络访问)导致 NetworkOnMainThreadException 。正因为如此,我想将它移动到的AsyncTask

I'm trying to check connection to the internet on Android (an actual connection, as opposed to network access) which causes NetworkOnMainThreadException. Because of this I'm trying to move it into an AsyncTask.

这是我的 isConnected()方法:

if(!checkNetwork(parent)){
    return false;
}
if(!checkConnection(url)){
    return false;
}
return true;

现在,我检查只需使用如果(isConnected()),但我得到异常的连接。因此,我需要做的是移动上述方法成的AsyncTask和检索它返回的值。

Now, I check the connection by just using if(isConnected()) but I'm getting the exception. So what I need to do is move the above method into an AsyncTask and retrieve the value it returns.

我想也许我可以做一个全局变量会保持它的轨道,但我不知道如果我的价值将之前或AsyncTask的已成立后退还。

I thought perhaps I could make a global variable that'd keep track of it, but then I'm not sure if my value would be returned before or after the AsyncTask had set it.

我敢肯定有办法做到这一点,所以我在寻找如何做到这一点的想法。任何意见是AP preciated!

I'm sure there are ways to do this, so I'm looking for ideas on how to do it. Any advice is appreciated!

编辑:我已经更新了我的code使用一个AsyncTask的,让我知道这看起来更好:

I've updated my code to use an AsyncTask, let me know if this looks better:

ConnectUtils.java:

ConnectUtils.java:

public class ConnectUtils {

    private static boolean hasConnected, hasChecked;

    public boolean isConnected(Context parent, String url){ 
        hasChecked = false;
        this.new CheckURL(parent, url).execute();
        while(!hasChecked){ }
        return hasConnected;
    }

    private class CheckURL extends AsyncTask<Void, Void, Boolean>{

        private Context parent;
        private String url;

        public CheckURL(Context parent, String url){
            this.parent = parent;
            this.url = url;
        }

        @Override
        protected Boolean doInBackground(Void... params){
            if(!checkNetwork(parent)){
                return false;
            }
            if(!checkConnection(url)){
                return false;
            }
            return true;
        }

        @Override
        protected void onPostExecute(Boolean result){
            super.onPostExecute(result);
            hasConnected = result;
            hasChecked = true;
        }
    }

    private static boolean checkNetwork(Context parent){
        ConnectivityManager conMgr = (ConnectivityManager)parent.getSystemService(Context.CONNECTIVITY_SERVICE);
        if(conMgr.getActiveNetworkInfo() != null){
            NetworkInfo activeInfo = conMgr.getActiveNetworkInfo();
            if(!activeInfo.isConnected() || !activeInfo.isAvailable()){
                return false;
            }
            return true;
        }
        return false;
    }

    private static boolean checkConnection(String url){
        boolean responded = false;
        HttpGet requestTest = new HttpGet(url);
        HttpParams params = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(params, 3000);
        HttpConnectionParams.setSoTimeout(params, 5000);
        DefaultHttpClient client = new DefaultHttpClient(params);
        try {
            client.execute(requestTest);
            responded = true;
        } catch (Exception e){
            e.printStackTrace();
        }
        return responded;
    }
}

通过称为如果(!新ConnectUtils()。isConnected(这一点,http://google.com))

推荐答案

下面是一个示例code:

here's a sample code:

new AsyncTask<Void, Void, Boolean>()
{
    @Override
    protected Boolean doInBackground(Void... p)
    {
        return isConnected();
    }

    @Override
    protected void onPostExecute(Boolean result)
    {
        //this is code for the UI thread, now that it knows what is the result.
    }
}.execute();