How to check internet access on Android? InetAddress never times out

后端 未结 30 4350
猫巷女王i
猫巷女王i 2020-11-21 04:45

I got a AsyncTask that is supposed to check the network access to a host name. But the doInBackground() is never timed out. Anyone have a clue?

30条回答
  •  没有蜡笔的小新
    2020-11-21 05:04

    For me it was not a good practice to check the connection state in the Activity class, because

    ConnectivityManager cm =
        (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    

    should be called there, or you need to push down your Activity instance (context) to the connection handler class to able to check the connection state there When no available connection (wifi, network) I catch the UnknownHostException exception:

    JSONObject jObj = null;
    Boolean responded = false;
    HttpGet requestForTest = new HttpGet("http://myserver.com");
    try {
        new DefaultHttpClient().execute(requestForTest);
        responded = true;
    } catch (UnknownHostException e) {
        jObj = new JSONObject();
        try {
            jObj.put("answer_code", 1);
            jObj.put("answer_text", "No available connection");
        } catch (Exception e1) {}
        return jObj;
    } catch (IOException e) {
        e.printStackTrace();
    }
    

    In this way I can handle this case along with the other cases in the same class (my server always response back with a json string)

提交回复
热议问题