Android:检查互联网连接会挂起UI

时间:2016-07-26 23:52:16

标签: java android

在我的应用程序中,我显示一个带有RETRY按钮的ErrorFragment对象,如果没有,则重新检查互联网。但是,当用户建立了互联网连接并单击了“重试”按钮时,UI会挂起几秒钟。

我知道不要在主线程上执行此任务,所以我实现了以下内容:

public class MainFragment extends VerticalGridFragment
{
    ....

    if (isConnectedToInternet() == true)
    {
        // Load data
    }
    else
    {
        displayInternetError();
    }

    public void displayInternetError()
    {
        Log.d(TAG, "displayInternetError");

        final ErrorFragment error = new ErrorFragment();

        getFragmentManager().beginTransaction().replace(R.id.main_browse_fragment, error)
                .commit();

        error.setImageDrawable(getResources().getDrawable(R.drawable.lb_ic_sad_cloud, null));
        error.setMessage(getResources().getString(R.string.no_internet_message));
        error.setDefaultBackground(true);

        error.setButtonText(getResources().getString(R.string.retry_connection));

        error.setButtonClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View arg0)
            {
                if (isConnectedToInternet() == true)
                {
                    getFragmentManager().beginTransaction().remove(error).commit();
                    getFragmentManager().popBackStack();

                    Singleton.getInstance().setInternetErrorShown(false);
                    prepareBackgroundManager();
                    setupFragment();
                    setupEventListeners();
                }
                else
                {
                    Singleton.getInstance().setInternetErrorShown(true);
                }
            }
        });
    }

    ...

     private class GetInternetStatus extends AsyncTask<Void,Void,Boolean>
    {
        @Override
        protected Boolean doInBackground(Void... params)
        {
            return hasInternetAccess();
        }

        protected boolean hasInternetAccess()
        {
            try
            {
                URL url = new URL("http://www.google.com");

                HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
                urlc.setRequestProperty("User-Agent", "Android Application:1");
                urlc.setRequestProperty("Connection", "close");
                urlc.setConnectTimeout(1000 * 30);
                urlc.connect();

                // http://www.w3.org/Protocols/HTTP/HTRESP.html
                if (urlc.getResponseCode() == 200 || urlc.getResponseCode() > 400)
                {
                    // Requested site is available
                    return true;
                }
            }
            catch (Exception ex)
            {
                // Error while trying to connect
                ex.printStackTrace();
                return false;
            }
            return false;
        }
    }

    // Checking for all possible internet connections
    public  boolean isConnectedToInternet()
    {
        Boolean result = false;

        try
        {
            // Get the result after executing AsyncTask
            result = new GetInternetStatus().execute().get();
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
        catch (ExecutionException e)
        {
            e.printStackTrace();
        }
        return result;
    }

    ....
}

但它仍然挂起,UI没有响应。我该如何解决这个问题?

由于

1 个答案:

答案 0 :(得分:1)

它会挂起用户界面,因为即使您使用的是AsyncTask,也会启动它,然后立即尝试获取结果。相反,请使用AsyncTask的{​​{1}加载数据或调用onPostExecute

的方法