네트워크나 서버 연결 여부를 판단하는 도구 클래스

1904 단어
package com.example.until;

import java.io.IOException;

import java.net.HttpURLConnection;

import java.net.MalformedURLException;

import java.net.URL;

import android.app.Activity;

import android.content.Context;

import android.net.ConnectivityManager;

import android.net.NetworkInfo;

public class NetWork {


    /**
     *  
     * 
     * @return
     */
    public boolean isNetworkAvailable(Activity activity) {
        Context context = activity.getApplicationContext();
        //  ( wi-fi,net )
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager == null) {
            return false;
        } else {
            //  NetworkInfo 
            NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();
            if (networkInfo != null && networkInfo.length > 0) {
                for (int i = 0; i < networkInfo.length; i++) {
                    //  NetworkInfo.State.CONNECTED 
                    if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    /**
     *  
     * 
     * @return
     */
    public boolean isConnByHttp() {
        boolean isConn = false;
        URL url;
        HttpURLConnection conn = null;
        try {
            url = new URL("http://" + APPFinal.getip());
            conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(50);
            if (conn.getResponseCode() == 200) {
                isConn = true;
            }
        } catch (MalformedURLException e) {

        } catch (IOException e) {

        } finally {
            conn.disconnect();
        }
        return isConn;
    }

}

좋은 웹페이지 즐겨찾기