2016-09-16 2 views
1

Google에 핑 (ping)하여 인터넷 연결 상태를 확인하고 있습니다. 문제는 연결이없고 대기 시간이 지나치게 확장되었을 때입니다. 그것은 boolean을 반환하기 때문에인터넷 연결 확인을위한 시간 초과 Android

private boolean checkInternet() { 
    String netAddress = null; 
    try 
    { 
     netAddress = new NetTask().execute("www.google.com").get(); 
     return (!netAddress.equals("")); 
    } 
    catch (Exception e1) 
    { 
     e1.printStackTrace(); 
     return false; 
    } 
    return false; 
} 

public class NetTask extends AsyncTask<String, Integer, String> 
{ 
    @Override 
    protected String doInBackground(String... params) 
    { 
     InetAddress addr = null; 
     try 
     { 
       addr = InetAddress.getByName(params[0]); 
     } 
     catch (UnknownHostException e) 
     { 
      e.printStackTrace(); 
      return ""; 
     } catch (IOException time) 
     { 
      time.printStackTrace(); 
      return ""; 
     } 
     return addr.getHostAddress(); 
    } 
} 

내가 isReachable(int timeout)을 연결할 수 없습니다

내 코드입니다. 어떻게 해결할 수 있습니까?

답변

0

메소드가 할당 된 시간 내에 완료되지 않으면 메소드를 취소 할 수있는 몇 가지 방법이 있습니다.

첫 번째 대답은 to this question 일 것입니다. 여기에 귀하의 예가 들어 있습니다.

ExecutorService executor = Executors.newCachedThreadPool(); 
Callable<Object> task = new Callable<Object>() { 
    public Object call() { 
     String netAddress = new NetTask().execute("www.google.com").get(); 
     return (!netAddress.equals("")); 
    } 
}; 
Future<Object> future = executor.submit(task); 
try{ 
    //Give the task 5 seconds to complete 
    //if not it raises a timeout exception 
    Object result = future.get(5, TimeUnit.SECONDS); 
    //finished in time 
    return result; 
}catch (TimeoutException ex){ 
    //Didn't finish in time 
    return false; 
} 
+0

코드에는 해당 예외가 완벽하게 추가됩니다. 부울 변수 결과를 형변환해야했습니다. 고마워요! – Mike