2015-02-01 5 views
0

두 가지 방법으로 인터넷 연결을 확인하는 안드로이드 프로그램을 작성하려고합니다. 첫 번째 방법은 가장 일반적인 방법 인 CheckInternetConnection()이고, 두 번째 방법은 웹 사이트 ConnectGoogleTest()에 연결하는 것입니다. 첫 번째 작품은 완벽하게 작동하지만 두 번째 작품에서는 내 태블릿이 멈 춥니 다! 아무도 왜 그런지 압니까?안드로이드 프로그래밍에서 인터넷 연결 확인

코드는 :

public class myITClass { 
private Context ctx ; 
public myITClass(Context context){ 
    this.ctx = context; 
} 

public boolean CheckInternetConnection() { 
    ConnectivityManager cm = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE); 
    //NetworkInfo ni = cm.getActiveNetworkInfo(); 
    if (cm.getActiveNetworkInfo() == null) { 
     // There are no active networks. 
     return false; 
    } else { 

     return true; 
    } 
    } 
public boolean googlePingTest(){ 
    boolean res = false ; 
    try { 
     URL url = new URL("http://www.google.com/"); 
     HttpURLConnection urlc = (HttpURLConnection) url.openConnection(); 
     urlc.setConnectTimeout(15000); 
     urlc.connect(); 
     if (urlc.getResponseCode() == 200) { res = true; } 
    } catch (MalformedURLException e1) { 
     res = false; 
    } catch (IOException e) { 
     res = false ; 
    }catch (Exception e){ 
     res = false ; 
    } 

    return res; 
} 
} 
+0

()':

PingTask ping = new PingTask(); ping.execute(); 

이 상태를 가져옵니다. logcat에있는 게있어? –

+0

나는 여기서도 똑같은 대답을하고있다. 연결에 설정된 속성은 거의 차이가 없었습니다. http://stackoverflow.com/questions/27988103/android-check-if-there-is-wifi-but-no-internet – Rohit5k2

답변

1

~ http://www.google.com/ ~ HttpURLConnection까지 보낼 수 있습니다. 당신이 배경 스레드에서 그것을하고 있는지 확인하십시오. 네트워크 태스크 생성은 백그라운드에서 실행해야합니다. 그렇게 할 수있는 3 개 가지 옵션이 있습니다 :

를 사용하여, 우리는 AsyncTask을 사용합니다. 그래서 Activity 내부에 private 클래스를 만듭니다

private boolean res = false; 
private class PingTask extends AsyncTask<String, String, String> { 

    @Override 
    protected String doInBackground(String... urlSite) { 
     HttpURLConnection urlc = null; 

     try { 
      URL url = new URL("http://www.google.com/"); 
      urlc = (HttpURLConnection) url.openConnection(); 
      urlc.setConnectTimeout(15000); 
      urlc.setRequestMethod("GET"); 
      urlc.connect(); 

     if (urlc.getResponseCode() == 200) { res = true; } 
     } catch (MalformedURLException e1) { 
     res = false; 
     } catch (IOException e) { 
     res = false ; 
     }catch (Exception e){ 
     res = false ; 
     }finally{ 
      if (urlc != null) { 
       try{ 
        // close the connection 
        urlc.disconnect(); 
       }catch (Exception e){ 
        e.printStackTrace(); 
       } 
      } 
     } 
     return null; 
    } 
} 

클래스에이 필드를 추가하는 것을 잊지 마세요 :

public boolean getStatus(){ 
    return status; 
} 

: 상태를 얻을 수

private boolean res = false; 

이 방법을 만들기 사용 방법?

PingTask 첫 번째 상태를 확인하기 위해 실행 : 난 당신이`대해서 openConnection을 호출 _after_ 연결 제한 시간을 설정할 수 있다고 생각하지 않습니다

// if the connection is available 
if(getStatus()==true){ 
    // do your thing here. 
} 
0

번째 방법은 메인 쓰레드에 동기 네트워크를 호출하고, 그 블록 UI. 그것을 위해 AsyncTask를 사용해보십시오.