android - 单击按钮检查互联网连接

标签 android android-asynctask httpurlconnection

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用于互联网连接检查。但由于他们没有使用 asynctask,如果我使用此代码,我将得到 NetworkOnMainThreadException。我尝试使用 asynctask,但现在我只收到消息“Internet 连接不可用”。我认为这是因为 asynctask 没有返回 bool 值 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" />

关于android - 单击按钮检查互联网连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35647067/

相关文章:

java - Android: ListView 的 android:dividerHeight 的默认值是多少

android - 如何获取日历事件集的状态与否

java - Android:AsyncTask 内的 Java Net Socket 异常

android - 当使用 android 4.x 运行异步任务时如何处理屏幕方向变化

java - 模拟 HTTPSURLConnection 类抛出 java.lang.AbstractMethodError

java - 如何使用java.net.URLConnection在php web表单中获取验证码图像

java - Backendless - 我应该从服务订阅 channel 吗?

android - Google Play 游戏登录流程

java - 如何依次运行两个异步任务?

android - 无法在 45 秒内启动 Intent。也许主线程在合理的时间内没有空闲?