17

How to use try to capture instead near force?

 3 years ago
source link: https://www.codesd.com/item/how-to-use-try-to-capture-instead-near-force.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

How to use try to capture instead near force?

advertisements

I have this code in android and java. I want to show a dialog to the user when his Internet connection has problems or the website is inaccessible. I try to put my code into a try-catch block but yet when the Internet connection has a problem my app is closed. I want to show a message to the user, not to close the app.

 HttpPost ht = new HttpPost("http://yahoo.com");
        HttpClient hc = new DefaultHttpClient();
        HttpResponse hr = null;

        try {
            hr = hc.execute(ht);

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        String htmlTemp = "";
        try {

            HttpEntity he = hr.getEntity();

            htmlTemp = new String(EntityUtils.toString(he));

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


you can try to add UnknownHostException to your catch, or you can use this method before calling request :

  public static boolean hasConnection() {
    ConnectivityManager cm = (ConnectivityManager) MbridgeApp.getContext().getSystemService(
        Context.CONNECTIVITY_SERVICE);

    NetworkInfo wifiNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    if (wifiNetwork != null && wifiNetwork.isConnected()) {
      return true;
    }

    NetworkInfo mobileNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    if (mobileNetwork != null && mobileNetwork.isConnected()) {
      return true;
    }

    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    if (activeNetwork != null && activeNetwork.isConnected()) {
      return true;
    }

    return false;
  }


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK