Perform network operation to check if user has internet connection with async task

橙三吉。 提交于 2020-01-06 21:01:48

问题


I am getting below exception

android.os.NetworkOnMainThreadException

because I don't use an async task to make the particular network operation. I have searched for this, but it got me so confused. Could someone make it work with async task and the particular functions?

Below are two functions i use :

1) isNetworkAvailable()

private boolean isNetworkAvailable() {

    ConnectivityManager connectivityManager
            = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null;

}

2) hasInternetAccess(Boolean showMessage)

When i want to display a toast i call this function, setting the parameter to true.

public boolean hasInternetAccess(Boolean showMessage) {

    if (isNetworkAvailable()) {
        try {
            HttpURLConnection urlc = (HttpURLConnection)
                    (new URL("http://clients3.google.com/generate_204")
                            .openConnection());
            urlc.setRequestProperty("User-Agent", "Android");
            urlc.setRequestProperty("Connection", "close");
            urlc.setConnectTimeout(1500);
            urlc.connect();
            return (urlc.getResponseCode() == 204 &&
                    urlc.getContentLength() == 0);
        } catch (IOException e) {
            Log.w("connection", "Error checking internet connection", e);
        }
    } else {
        if(showMessage) // If i want to show the toast, it's true
            showAToast("No Internet Connection", Toast.LENGTH_SHORT); // Just another function to show a toast
    }
    return false;
}

回答1:


This is how you can use an AsyncTask by creating an inner class which extends AsyncTask.

private class NetworkInAsync extends AsyncTask<String, Void, Boolean> {

    private Context context;
    private Activity activity;

    NetworkInAsync(Activity activity) {
        this.context = activity.getApplicationContext();
        this.activity = activity;
    }


    @Override
    protected void onPreExecute() {
    }

    @Override
    protected void onPostExecute(Boolean result) {
        // Do something with the result here 
    }

    @Override
    protected Boolean doInBackground(String... params) {
        if (isNetworkAvailable()) {
            try {
                HttpURLConnection urlc = (HttpURLConnection)
                (new URL("http://clients3.google.com/generate_204")
                        .openConnection());
                urlc.setRequestProperty("User-Agent", "Android");
                urlc.setRequestProperty("Connection", "close");
                urlc.setConnectTimeout(1500);
                urlc.connect();
                return (urlc.getResponseCode() == 204 &&
                urlc.getContentLength() == 0);
            } catch (IOException e) {
                Log.w("connection", "Error checking internet connection", e);
            }
        } else {
            if(showMessage) // If i want to show the toast, it's true
            showAToast("No Internet Connection", Toast.LENGTH_SHORT); // Just another function to show a toast
        }
        return false;
    }
}

You can execute the AsyncTask as follows

new NetworkInAsync(this).execute();

I would still recommend you go through the docs here to clarify yourself how AsyncTask works in Android.




回答2:


The code should work when you call it from AsyncTask's doInBackground method

call test();

private void test() {
HttpURLConnection urlc = (HttpURLConnection)
                    (new URL("http://clients3.google.com/generate_204")
                            .openConnection());

            urlc.setConnectTimeout(1500);
            urlc.connect();
}

You can check the network connection before making the call, but any how, you should catch the exception in TimeOut exception. So I dont think, that you have any much benifit to check the connectivity before making the call.



来源:https://stackoverflow.com/questions/39306219/perform-network-operation-to-check-if-user-has-internet-connection-with-async-ta

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!