Android检查互联网连接

我想创建一个使用互联网的应用程序,我试图创建一个函数,检查连接是否可用,如果不是,请转到具有重试按钮和解释的活动。

附件是我的代码到目前为止,但我收到错误Syntax error, insert "}" to complete MethodBody.

现在我一直在试图让它的工作,但迄今没有运气…任何帮助将不胜感激。

 public class TheEvoStikLeagueActivity extends Activity { private final int SPLASH_DISPLAY_LENGHT = 3000; /** Called when the activity is first created. */ @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); private boolean checkInternetConnection() { ConnectivityManager conMgr = (ConnectivityManager) getSystemService (Context.CONNECTIVITY_SERVICE); // ARE WE CONNECTED TO THE NET if (conMgr.getActiveNetworkInfo() != null && conMgr.getActiveNetworkInfo().isAvailable() && conMgr.getActiveNetworkInfo().isConnected()) { return true; /* New Handler to start the Menu-Activity * and close this Splash-Screen after some seconds.*/ new Handler().postDelayed(new Runnable() { public void run() { /* Create an Intent that will start the Menu-Activity. */ Intent mainIntent = new Intent(TheEvoStikLeagueActivity.this, IntroActivity.class); TheEvoStikLeagueActivity.this.startActivity(mainIntent); TheEvoStikLeagueActivity.this.finish(); } }, SPLASH_DISPLAY_LENGHT); } else { return false; Intent connectionIntent = new Intent(TheEvoStikLeagueActivity.this, HomeActivity.class); TheEvoStikLeagueActivity.this.startActivity(connectionIntent); TheEvoStikLeagueActivity.this.finish(); } } } 

此方法检查移动设备是否连接到互联网,如果连接则返回true:

 private boolean isNetworkConnected() { ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); return cm.getActiveNetworkInfo() != null; } 

在清单中,

 <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 

编辑:这种方法实际上检查设备是否连接到互联网(有可能它连接到网络,但不是互联网)。

 public boolean isInternetAvailable() { try { InetAddress ipAddr = InetAddress.getByName("google.com"); //You can replace it with your name return !ipAddr.equals(""); } catch (Exception e) { return false; } } 

检查以确保它“连接”到网络:

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

检查以确保它“连接”到网络:

 public boolean isInternetAvailable() { try { final InetAddress address = InetAddress.getByName("www.google.com"); return !address.equals(""); } catch (UnknownHostException e) { // Log error } return false; } 

需要许可:

 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 

https://stackoverflow.com/a/17583324/950427

你可以简单地ping一个在线网站,如谷歌:

 public boolean isConnected() throws InterruptedException, IOException { String command = "ping -c 1 google.com"; return (Runtime.getRuntime().exec (command).waitFor() == 0); } 

上述方法在连接到Wi-Fi资源或通过手机数据包时有效。 但是在Wi-Fi连接的情况下,有些情况下您还需要像在咖啡厅一样登录。 所以在这种情况下,你的应用程序将会因为你连接到Wi-Fi源而不是在互联网上而失败。

这种方法工作正常。

  public static boolean isConnected(Context context) { ConnectivityManager cm = (ConnectivityManager)context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); if (activeNetwork != null && activeNetwork.isConnected()) { try { URL url = new URL("http://www.google.com/"); HttpURLConnection urlc = (HttpURLConnection)url.openConnection(); urlc.setRequestProperty("User-Agent", "test"); urlc.setRequestProperty("Connection", "close"); urlc.setConnectTimeout(1000); // mTimeout is in seconds urlc.connect(); if (urlc.getResponseCode() == 200) { return true; } else { return false; } } catch (IOException e) { Log.i("warning", "Error checking internet connection", e); return false; } } return false; } 

请在与主线程分开的线程中使用它,因为它会进行网络调用,如果不遵循,将抛出NetwrokOnMainThreadException。

也不要把这个方法放在onCreate或其他方法里面。 把它放在一个班级,并访问它。

你不能在另一个方法内创建一个方法,移动private boolean checkInternetConnection() {方法private boolean checkInternetConnection() {

接受的答案的编辑显示如何检查互联网上可以达到的东西。 如果情况并非如此,那么我必须等待太久才能得到答案(使用没有互联网连接的WiFi)。 不幸的是InetAddress.getByName没有超时参数,所以接下来的代码是围绕这个工作的:

 private boolean internetConnectionAvailable(int timeOut) { InetAddress inetAddress = null; try { Future<InetAddress> future = Executors.newSingleThreadExecutor().submit(new Callable<InetAddress>() { @Override public InetAddress call() { try { return InetAddress.getByName("google.com"); } catch (UnknownHostException e) { return null; } } }); inetAddress = future.get(timeOut, TimeUnit.MILLISECONDS); future.cancel(true); } catch (InterruptedException e) { } catch (ExecutionException e) { } catch (TimeoutException e) { } return inetAddress!=null && !inetAddress.equals(""); } 

你可以使用下面的代码来检查Internet连接。

这将有用的两种方式,您可以检查哪种类型的网络连接是可用的,所以你可以做这样的过程。

你只需要复制下面的类并直接粘贴到你的包中。

 /** * * @author Pratik Butani * */ public class InternetConnection { /** CHECK WHETHER INTERNET CONNECTION IS AVAILABLE OR NOT */ public static boolean checkConnection(Context context) { final ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connMgr.getActiveNetworkInfo(); if (activeNetworkInfo != null) { // connected to the internet Toast.makeText(context, activeNetworkInfo.getTypeName(), Toast.LENGTH_SHORT).show(); if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI) { // connected to wifi return true; } else if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE) { // connected to the mobile provider's data plan return true; } } return false; } } 

现在你可以使用像:

 if (InternetConnection.checkConnection(context)) { // Its Available... } else { // Not Available... } 

不要忘记取得许可:) 🙂

 <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> 

您可以根据您的要求进行修改。

谢谢。

不需要很复杂。 最简单和框架的方式是使用ACCESS_NETWORK_STATE权限,只是建立一个连接的方法

 public boolean isOnline() { ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnectedOrConnecting(); } 

你也可以使用requestRouteToHost如果你有一个requestRouteToHost主机和连接类型(无线/移动)在脑海中。

您还需要:

 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 

在你的Android清单。

欲了解更多详情, 请点击

所有的官方方法只告诉天气设备是否开放网络,
如果您的设备连接到Wifi,但Wifi没有连接到互联网,那么这些方法将失败(这发生很多时间),没有内置的网络检测方法将告诉这种情况下,所创建的异步回调类将返回onConnectionSuccessonConnectionFail

  new CheckNetworkConnection(this, new CheckNetworkConnection.OnConnectionCallback() { @Override public void onConnectionSuccess() { Toast.makeText(context, "onSuccess()", toast.LENGTH_SHORT).show(); } @Override public void onConnectionFail(String msg) { Toast.makeText(context, "onFail()", toast.LENGTH_SHORT).show(); } }).execute(); 

来自异步任务的网络呼叫

 public class CheckNetworkConnection extends AsyncTask<Void, Void, Boolean> { private OnConnectionCallback onConnectionCallback; private Context context; public CheckNetworkConnection(Context con, OnConnectionCallback onConnectionCallback) { super(); this.onConnectionCallback = onConnectionCallback; this.context = con; } @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected Boolean doInBackground(Void... params) { if (context == null) return false; boolean isConnected = new NetWorkInfoUtility().isNetWorkAvailableNow(context); return isConnected; } @Override protected void onPostExecute(Boolean b) { super.onPostExecute(b); if (b) { onConnectionCallback.onConnectionSuccess(); } else { String msg = "No Internet Connection"; if (context == null) msg = "Context is null"; onConnectionCallback.onConnectionFail(msg); } } public interface OnConnectionCallback { void onConnectionSuccess(); void onConnectionFail(String errorMsg); } } 

将ping到服务器的实际类

 class NetWorkInfoUtility { public boolean isWifiEnable() { return isWifiEnable; } public void setIsWifiEnable(boolean isWifiEnable) { this.isWifiEnable = isWifiEnable; } public boolean isMobileNetworkAvailable() { return isMobileNetworkAvailable; } public void setIsMobileNetworkAvailable(boolean isMobileNetworkAvailable) { this.isMobileNetworkAvailable = isMobileNetworkAvailable; } private boolean isWifiEnable = false; private boolean isMobileNetworkAvailable = false; public boolean isNetWorkAvailableNow(Context context) { boolean isNetworkAvailable = false; ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); setIsWifiEnable(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected()); setIsMobileNetworkAvailable(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnected()); if (isWifiEnable() || isMobileNetworkAvailable()) { /*Sometime wifi is connected but service provider never connected to internet so cross check one more time*/ if (isOnline()) isNetworkAvailable = true; } return isNetworkAvailable; } public boolean isOnline() { /*Just to check Time delay*/ long t = Calendar.getInstance().getTimeInMillis(); Runtime runtime = Runtime.getRuntime(); try { /*Pinging to Google server*/ Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8"); int exitValue = ipProcess.waitFor(); return (exitValue == 0); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } finally { long t2 = Calendar.getInstance().getTimeInMillis(); Log.i("NetWork check Time", (t2 - t) + ""); } return false; } } 

使用这个方法:

 public static boolean isOnline() { ConnectivityManager cm = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo(); return netInfo != null && netInfo.isConnectedOrConnecting(); } 

这是需要的权限:

 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 

试试下面的代码:

 public static boolean isNetworkAvailable(Context context) { boolean outcome = false; if (context != null) { ConnectivityManager cm = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo[] networkInfos = cm.getAllNetworkInfo(); for (NetworkInfo tempNetworkInfo : networkInfos) { /** * Can also check if the user is in roaming */ if (tempNetworkInfo.isConnected()) { outcome = true; break; } } } return outcome; } 

在清单中

 <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 

在代码中,

 public static boolean isOnline(Context ctx) { if (ctx == null) return false; ConnectivityManager cm = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo(); if (netInfo != null && netInfo.isConnectedOrConnecting()) { return true; } return false; } 

在“返回”语句之后,你不能写任何代码(try-finally块除外)。 在“返回”语句之前移动新的活动代码。

 public boolean checkInternetConnection(Context context) { ConnectivityManager connectivity = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivity == null) { return false; } else { NetworkInfo[] info = connectivity.getAllNetworkInfo(); if (info != null) { for (int i = 0; i < info.length; i++){ if (info[i].getState()==NetworkInfo.State.CONNECTED){ return true; } } } } return false; } 

使用此代码来检查互联网连接

 ConnectivityManager connectivityManager = (ConnectivityManager) ctx .getSystemService(Context.CONNECTIVITY_SERVICE); if ((connectivityManager .getNetworkInfo(ConnectivityManager.TYPE_MOBILE) != null && connectivityManager .getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED) || (connectivityManager .getNetworkInfo(ConnectivityManager.TYPE_WIFI) != null && connectivityManager .getNetworkInfo(ConnectivityManager.TYPE_WIFI) .getState() == NetworkInfo.State.CONNECTED)) { return true; } else { return false; } 

这是一个我用作Utils类的一部分的函数:

 public static boolean isNetworkConnected(Context context) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); return (cm.getActiveNetworkInfo() != null) && cm.getActiveNetworkInfo().isConnectedOrConnecting(); } 

像这样使用它: Utils.isNetworkConnected(MainActivity.this);

1-创建新的java文件(右键单击包。new> class>命名文件ConnectionDetector.java

2-将以下代码添加到文件中

 <pre>package <add you package name> example com.example.example; import android.content.Context; import android.net.ConnectivityManager; public class ConnectionDetector { private Context mContext; public ConnectionDetector(Context context){ this.mContext = context; } public boolean isConnectingToInternet(){ ConnectivityManager cm = (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE); if(cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected() == true) { return true; } return false; } } 

3-打开你的MainActivity.java – 你想要检查连接的活动,然后执行以下操作

A-创建和定义功能。

 <pre>ConnectionDetector mConnectionDetector;</pre> 

B-在“OnCreate”里添加以下内容

 <pre>mConnectionDetector = new ConnectionDetector(getApplicationContext());</pre> 

c-检查连接使用以下步骤

 <pre> if (mConnectionDetector.isConnectingToInternet() == false) { //no connection- do something } else { //there is connection }</pre> 

我有问题的IsInternetAvailable答案不测试蜂窝网络,而只有在无线连接。 这个答案适用于WiFi和移动数据:

如何检查网络连接启用或禁用在移动WIFI和3G(数据计划)?

这是处理所有情况的另一种选择:

 public void isNetworkAvailable() { ConnectivityManager connectivityManager = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); if (activeNetworkInfo != null && activeNetworkInfo.isConnected()) { } else { Toast.makeText(ctx, "Internet Connection Is Required", Toast.LENGTH_LONG).show(); } } 

检查网络在Android与互联网数据速度可用。

 public boolean isConnectingToInternet(){ ConnectivityManager connectivity = (ConnectivityManager) Login_Page.this.getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivity != null) { NetworkInfo[] info = connectivity.getAllNetworkInfo(); if (info != null) for (int i = 0; i < info.length; i++) if (info[i].getState() == NetworkInfo.State.CONNECTED) { try { HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection()); urlc.setRequestProperty("User-Agent", "Test"); urlc.setRequestProperty("Connection", "close"); urlc.setConnectTimeout(500); //choose your own timeframe urlc.setReadTimeout(500); //choose your own timeframe urlc.connect(); int networkcode2 = urlc.getResponseCode(); return (urlc.getResponseCode() == 200); } catch (IOException e) { return (false); //connectivity exists, but no internet. } } } return false; } 

这个函数返回true或false。 必须获得用户权限

  <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />