2014-04-25 2 views
1

다음 코드를 사용하고 있으며 인터넷 연결이되어 있는지 프로그래밍 방식으로 확인하는 중입니다.
NetworkOnMainThreadException이 발생하고 AsyncTask를 사용하는 것이 좋습니다.
hasActiveInternetConnection(Context context)에서 네트워크 작업을 수행하고 네트워크에 연결되어 있으면 true를 반환하고 그렇지 않으면 false를 반환하고 싶습니다.
어떻게 AsyncTask를 사용하여이 작업을 수행합니까?AsyncTask를 사용하여 인터넷 연결을 확인하는 방법

public class NetworkUtil extends AsyncTask<String, Void, String>{ 
     Context context; 

     public NetworkUtil(Context context){ 
      this.context = context; 
     } 

    private ProgressDialog dialog; 

    @Override 
    protected void onPreExecute() { 

     super.onPreExecute(); 
    } 

    @Override 
    protected String doInBackground(String... arg0) { 
     if (new CheckNetwork(context).isNetworkAvailable()) 
     { 
      try { 
       HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection()); 
       urlc.setRequestProperty("User-Agent", "Test"); 
       urlc.setRequestProperty("Connection", "close"); 
       urlc.setConnectTimeout(1500); 
       urlc.connect(); 
       boolean url= (urlc.getResponseCode() == 200); 
       String str = String.valueOf(url); 
       return str; 
      } catch (IOException e) { 

      } 
     } 


      // your get/post related code..like HttpPost = new HttpPost(url); 
     else { 
      Toast.makeText(context, "no internet!", Toast.LENGTH_SHORT).show(); 
     } 


     return null; 
    } 
    @Override 
    protected void onPostExecute(String result) { 
     super.onPostExecute(result); 
     if (dialog.isShowing()) { 
      dialog.dismiss(); 
     } 
    } 
    } 
+0

당신이 연결이 아닌지 확인 할을이 자신의 코드 직원을 할? 직원에게 인터넷 연결이 될 때까지 기다리시겠습니까? –

+0

@ahmed 인터넷 연결을 확인하고 연결이 존재하면 true를 반환하고 싶습니다! – user3458008

답변

0
There is no way to get an Internet connexion state, you will always have the network connection state. 

하지만 꽤 좋은 대답 here을 발견 : 당신은 google.com에 요청을 보내! :) 당신이 원한다면 당신은 또한 유닉스 명령에 의해 구글에 핑 (ping)을 시도 할 수있다 !!

여기 사람이 스레드를 사용하고 있으며 응답을 기다리고 나서 부울을 반환합니다. 당신은 처리기에서 직원을 수행합니다. 내가 핸들러 정의, 그리고

public static void isNetworkAvailable(final Handler handler, final int timeout) { 
    // ask fo message '0' (not connected) or '1' (connected) on 'handler' 
    // the answer must be send before before within the 'timeout' (in milliseconds) 

    new Thread() { 
     private boolean responded = false; 
     @Override 
     public void run() { 
      // set 'responded' to TRUE if is able to connect with google mobile (responds fast) 
      new Thread() {  
       @Override 
       public void run() { 
        HttpGet requestForTest = new HttpGet("http://m.google.com"); 
        try { 
         new DefaultHttpClient().execute(requestForTest); // can last... 
         responded = true; 
        } 
        catch (Exception e) { 
        } 
       } 
      }.start(); 

      try { 
       int waited = 0; 
       while(!responded && (waited < timeout)) { 
        sleep(100); 
        if(!responded) { 
         waited += 100; 
        } 
       } 
      } 
      catch(InterruptedException e) {} // do nothing 
      finally { 
       if (!responded) { handler.sendEmptyMessage(0); } 
       else { handler.sendEmptyMessage(1); } 
      } 
     } 
    }.start(); 
} 

:

Handler h = new Handler() { 
    @Override 
    public void handleMessage(Message msg) { 

     if (msg.what != 1) { // code if not connected 

     } else { // code if connected 

     } 
    } 
}; 

을 ... 그리고 테스트 시작 :

isNetworkAvailable(h,2000); // get the answser within 2000 ms 
+0

ty ...이 시도! – user3458008

+1

잘 작동합니다! 이것이 잘 작동하는지 잠시 후에 확인합니다. 코드에 대한 타이 : – user3458008

+0

흠 잡을 데없이 근무 : – user3458008

1

귀하의 AsyncTask은 다음과 같아야합니다

private class NetworkUtilTask extends AsyncTask<Void, Void, Boolean>{ 
    Context context; 

    public NetworkUtilTask(Context context){ 
     this.context = context; 
    } 

    protected Boolean doInBackground(Void... params) { 
     return hasActiveInternetConnection(this.context); 
    } 
    protected void onPostExecute(Boolean hasActiveConnection) { 
     Log.d(LOG_TAG,"Success=" + hasActiveConnection); 
    } 
} 

당신은 다음처럼 실행합니다 :

NetworkUtilTask netTask = new NetworkUtilTask(context); 
netTask.execute(); 
+1

좋은데, 옳은 대답이어야합니다. 비동기 작업에서 왜 이것을 사용하는지 이해하지 못했습니다. 이 팁의 장점이나 활용 사례를 설명해 주시겠습니까? –

+0

컨텍스트가 컨스트럭터에 전달되었으므로 Task 변수 'context'가 있기 때문에'this'를 사용했습니다. 기본적으로 이는 모호성을 피할뿐입니다. [this on read] (http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html) – meda

+0

보호 된 String doInBackground (String ... params)를 protected Boolean doInBackground로 변경할 수 없습니다. Void ... params) 어떻게해야합니까? 타이! – user3458008

3

사용하는 인터넷 연결을 확인하는이 클래스 ...

public class CheckNetwork { 
private Context context; 

public CheckNetwork(Context context) { 
    this.context = context; 
} 

public boolean isNetworkAvailable() { 
    ConnectivityManager connectivityManager = (ConnectivityManager) context 
      .getSystemService(Context.CONNECTIVITY_SERVICE); 
    NetworkInfo activeNetworkInfo = connectivityManager 
      .getActiveNetworkInfo(); 
    return activeNetworkInfo != null && activeNetworkInfo.isConnected(); 
} 

} 다음

.....

는 httppost에 대한이 ASynTask을 사용합니다.

public class NetworkUtil extends AsyncTask<String, Void, String> { 

private ProgressDialog dialog; 

@Override 
protected void onPreExecute() { 
    dialog = new ProgressDialog(YourActivity.this); 
    dialog.setMessage("Loading..."); 
    dialog.setCancelable(false); 
    dialog.show(); 
    super.onPreExecute(); 
} 

@Override 
protected String doInBackground(String... arg0) { 
    if (new CheckNetwork(YourActivity.this).isNetworkAvailable()) { 
     // your get/post related code..like HttpPost = new HttpPost(url); 
    } else { 
     // No Internet 
     // Toast.makeText(YourActivity.this, "no internet!", Toast.LENGTH_SHORT).show(); 
    } 
    return null; 
} 
@Override 
protected void onPostExecute(String result) { 
    super.onPostExecute(result); 
    if (dialog.isShowing()) { 
     dialog.dismiss(); 
    } 
} 
+0

정말 고마워요.위 코드를 업데이트했습니다 ... 올바른 방향으로 가고 있다면 확인해주십시오. 그리고 그 반환 str을 어떻게 얻습니까? 다른 클래스의 가치? 타이! – user3458008

+0

오른쪽으로 가면 두 가지 일을합니다 ... 1. NetworkUtil 클래스를 호출하는 동안 YourActivity를 보냅니다.이 것은 getApplicationContext()가 아닙니다. 2. str 변수를 클래스 변수로 만들고 bu 선언 ... ** public static String str; ** –

+0

... ** dialog = new ProgressDialog (YourActivity.is); dialog.setMessage ("Loading ..."); dialog.setCancelable (false); dialog.show(); ** onPreExecute() 메서드 –

관련 문제