如何使用Asynctask检查Internet连接

时间:2017-05-10 19:09:53

标签: android android-asynctask

您好我已经在堆栈中看到有关如何检查当前用户是否与互联网有效连接的教程和问题。我试图自己做,但我在AsyncTask中应用它时遇到了麻烦。

我自己尝试过,但我认为我做错了什么,我对AsyncTasks的了解并不是那么发达。我究竟做错了什么?

提前致谢! :d

这是我的MainActivity:

 private Button checkIntrnetButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    checkIntrnetButton = (Button) findViewById(R.id.checkInternetButton);
    checkIntrnetButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if(isOnline())
            {
               Toast.makeText(MainActivity.this,"YOU ARE ONLINE", Toast.LENGTH_SHORT).show();

                AsyncTaskRunner runner = new AsyncTaskRunner();
                runner.execute();
            }
            else
            {
                Toast.makeText(MainActivity.this,"YOU ARE NOT ONLINE", Toast.LENGTH_SHORT).show();
            }

        }
    });

}

protected boolean isOnline() {

    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        return true;
    } else {
        return false;
    }
}


private class AsyncTaskRunner extends AsyncTask<String, String, String> {

    ProgressDialog progressDialog;

    @Override
    protected String doInBackground(String... params) {

        if (isOnline()) {
            try {
                HttpURLConnection urlc = (HttpURLConnection) (new URL("http://clients3.google.com/generate_204").openConnection());
                urlc.setRequestProperty("User-Agent", "Test");
                urlc.setRequestProperty("Connection", "close");
                urlc.setConnectTimeout(1500);
                urlc.connect();
                boolean url = (urlc.getResponseCode() == 200);
                String str = String.valueOf(url);
                return str;
            } catch (IOException e) {
              }

        } else {
          Toast.makeText(MainActivity.this, "NO CONNECTION", Toast.LENGTH_SHORT).show();
        }
        return null;

    }


    @Override
    protected void onPostExecute(String result) {
        // execution of result of Long time consuming operation
        progressDialog.dismiss();
    }


    @Override
    protected void onPreExecute() {
        progressDialog = ProgressDialog.show(MainActivity.this,
                "ProgressDialog",
                "CHECKING NETWORK CONNECTION");
    }

}

1 个答案:

答案 0 :(得分:0)

由于我正在使用凌空来插入和检索所有数据,因此我一直在研究和试验有关错误onErrorResponse的问题。我发现了&#34; NetworkError,NoConnectionError和TimeoutError &#34;它帮助我解决了这个问题。

 @Override
                public void onErrorResponse(VolleyError error) {

                    if (error instanceof NetworkError) {
                        Toast.makeText(alcoholType.this,"THERE IS A PROBLEM WITH YOUR INTERNET CONNECTION", Toast.LENGTH_SHORT).show();
                       loading.dismiss();
                   }
                    else if (error instanceof NoConnectionError) {
                        Toast.makeText(alcoholType.this,"PLEASE SWITCH ON WIFI OR DATA", Toast.LENGTH_SHORT).show();
                        loading.dismiss();
                    }
                     else if (error instanceof TimeoutError) {
                       Toast.makeText(alcoholType.this,"Connection TimeOut! Please check your internet connection.", Toast.LENGTH_SHORT).show();
                        loading.dismiss();
                    }

                }

再次感谢所有帮助过的人! :d