2013-03-25 45 views
1

我需要检查Android应用上的Internet连接。在Android上检查Internet连接

我正在使用此代码:

ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); 
     NetworkInfo ni = cm.getActiveNetworkInfo(); 
     if (ni!=null && ni.isAvailable() && ni.isConnected()) { 
      return true; 
     } else { 
      return false; 
     } 

而且无法通过下一个错误:

The method getSystemService(String) is undefined for the type ConxsMTD

我尝试使用getContext().getSystemService也失败,下一个错误:

The method getContext() is undefined for the type ConxsMTD

任何想法我做错了什么?

+2

在这两种情况下,你使用的是不可用的方法在你使用它们的课堂上。这是基本的Java知识... – WarrenFaith 2013-03-25 18:52:04

回答

1

这不能解决你给出的例子,但我的例子确实有效,并且更简单(在我的脑海中)。

你想要做的是发送一个“ping”(如果你想调用它)来检查连接。如果连接完成,您知道您仍然连接。如果您获得IOExceptionNullPointerException,那么您可能超时并且不再连接。

try { 
    URL url = new URL("http://www.google.com"); 
    HttpURLConnection urlConnect = (HttpURLConnection) url.openConnection(); 
    urlConnect.setConnectTimeout(1000); 
    urlConnect.getContent(); 
    System.out.println("Connection established."); 
} catch (NullPointerException np) { 
    np.printStackTrace(); 
} catch (IOException io) { 
    io.printStackTrace(); 
} 
0

使用这个片段,我用它在每一个项目:

public static boolean checkNetworkState(Context context) { 
    ConnectivityManager conMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 
    NetworkInfo infos[] = conMgr.getAllNetworkInfo(); 
    for (NetworkInfo info : infos) { 
     if (info.getState() == State.CONNECTED) 
      return true; 
    } 
    return false; 
} 

所以,你只需通过getApplicationContext()这种方法就像boolean hasConnection = checkNetworkState(getApplicationContext());