android2019. 11. 27. 15:38

 

구글 홈페이지를 이용하여 실제 인터넷에 연결이 가능한지 여부를 확인


Thread connectionCheckThread = new Thread(){

        @Override
        public void run() {
            super.run();

            Context context = getApplicationContext();
            boolean result = isConnected(context);
            Log.d(LOG_TAG, "isConnected by thread : " + result);
            Message msg = mHandler.obtainMessage();
            msg.what=result ? 1 : 0;
            mHandler.sendMessage(msg);


        }
        public boolean isConnected(Context context) {
            ConnectivityManager cm = (ConnectivityManager)context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);

            NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
            if (activeNetwork != null && activeNetwork.isConnected()) {
                try {
                    URL url = new URL("http://www.google.com/");
                    HttpURLConnection urlc = (HttpURLConnection)url.openConnection();
                    urlc.setRequestProperty("User-Agent", "test");
                    urlc.setRequestProperty("Connection", "close");
                    urlc.setConnectTimeout(1000); // mTimeout is in seconds
                    urlc.connect();
                    if (urlc.getResponseCode() == 200) {
                        return true;
                    } else {
                        return false;
                    }
                } catch (IOException e) {
                    Log.e(LOG_TAG, "Error checking internet connection", e);
                    return false;
                }
            }

            return false;

        }

    };



출처: https://stackoverflow.com/questions/9570237/android-check-internet-connection 

'android' 카테고리의 다른 글

Android P native service 및 client 예제  (0) 2019.12.19
PDK에서 Android studio app을 gradle build 시 tips  (0) 2019.11.27
android alarm 세팅  (0) 2019.11.27
Android bp usage  (0) 2019.10.15
voice search later Android P  (0) 2019.09.26
Posted by easy16