public class MainActivity extends AppCompatActivity {
    Context context;

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

    }

    public void show(View v){
        if (hasActiveInternetConnection(context)){
            Toast.makeText(MainActivity.this, "Internet connection available", Toast.LENGTH_SHORT).show();
        }else{
            Toast.makeText(MainActivity.this, "Internet connection not available", Toast.LENGTH_SHORT).show();
        }
    }

    public boolean hasActiveInternetConnection(Context context) {
        if (isNetworkAvailable(context)) {

            new URLConnectTask().execute();


        } else {
           // Log.d(LOG_TAG, "No network available!");
            Toast.makeText(MainActivity.this, "No network available!", Toast.LENGTH_SHORT).show();
        }
        return false;
    }

    private class URLConnectTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... urls) {

            // params comes from the execute() call: params[0] is the url.
            try {
                HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
                urlc.setRequestProperty("User-Agent", "Test");
                urlc.setRequestProperty("Connection", "close");
                urlc.setConnectTimeout(1500);
                urlc.connect();
                String code = String.valueOf(urlc.getResponseCode() == 200);
                return code;
            } catch (IOException e) {
                //Log.e(LOG_TAG, "Error checking internet connection", e);
                //Toast.makeText(MainActivity.this, "Error checking internet connection", Toast.LENGTH_SHORT).show();
                return "Error checking internet connection";
            }
        }
    }

    private boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivityManager
                = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null;
    }
}


我将此post用于Internet连接检查。但是因为他们没有使用asynctask,所以如果我使用此代码,则会得到NetworkOnMainThreadException。我尝试使用asynctask,但现在仅收到消息“ Internet连接不可用”。我认为这是因为asynctask没有返回布尔值true。因此,任何帮助将不胜感激。

最佳答案

这项工作很好,您可以使用此代码

public boolean isConnectingToInternet(){
        ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
          if (connectivity != null)
          {
              NetworkInfo[] info = connectivity.getAllNetworkInfo();
              if (info != null)
                  for (int i = 0; i < info.length; i++)
                      if (info[i].getState() == NetworkInfo.State.CONNECTED)
                      {
                          return true;
                      }

          }
          return false;
    }

//add to permission <uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

10-05 22:53
查看更多