Check for Active internet connection Android

前端 未结 7 1645
不知归路
不知归路 2020-11-27 05:26

I am trying to write a part in my app that will differentiate between an Active Wifi connection and an actual connection to the internet. Finding out if there is an active

7条回答
  •  孤城傲影
    2020-11-27 05:42

    You can do it by create new parallel thread that count time :

    final class QueryClass {
        private int responseCode = -1;
         private   String makeHttpRequest(URL url) throws IOException {
                String jsonResponse = "";
                if(url == null) {
                    return null;
                }
    
                HttpURLConnection  urlConnection = null;
                InputStream inputStream = null;
                try {
                    urlConnection = (HttpURLConnection) url.openConnection();
                    urlConnection.setRequestMethod("GET");
                    urlConnection.setReadTimeout(5000 );
                    urlConnection.setConnectTimeout(5000 );
                    Thread thread = new Thread() {
                        @Override
                        public void run() {
                            super.run();
                            try {
                                sleep(5000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            if(responseCode == -1) {
                                //Perform error message
                            Intent intent = new Intent(context,ErrorsActivity.class);
                            intent.putExtra("errorTextMessage",R.string.errorNoInternet);
                            intent.putExtra("errorImage",R.drawable.no_wifi);
                            context.startActivity(intent);
                            }
                        }
                    };
                    thread.start();
                    urlConnection.connect();
                     responseCode = urlConnection.getResponseCode();
                    if (responseCode == 200) {
                        inputStream = urlConnection.getInputStream();
                        jsonResponse = readFromStream(inputStream);
    
                    }
    

提交回复
热议问题