How to check internet access on Android? InetAddress never times out
我有一个
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | public class HostAvailabilityTask extends AsyncTask<String, Void, Boolean> { private Main main; public HostAvailabilityTask(Main main) { this.main = main; } protected Boolean doInBackground(String... params) { Main.Log("doInBackground() isHostAvailable():"+params[0]); try { return InetAddress.getByName(params[0]).isReachable(30); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return false; } protected void onPostExecute(Boolean... result) { Main.Log("onPostExecute()"); if(result[0] == false) { main.setContentView(R.layout.splash); return; } main.continueAfterHostCheck(); } } |
如果设备处于飞行模式(或者在没有可用网络的其他情况下),
修改(Eddie的解决方案)如下:
1 2 3 4 5 6 | public boolean isOnline() { ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo(); return netInfo != null && netInfo.isConnectedOrConnecting(); } |
同时向
1 | <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> |
另一个小问题是,如果在给定时间点绝对需要网络连接,那么最好使用
网络连接/互联网接入
isConnectedOrConnecting() (在大多数答案中使用)检查是否有任何网络连接- 要知道这些网络中是否有任何一个可以访问Internet,请使用以下方法之一
a)ping服务器(简单)
1 2 3 4 5 6 7 8 9 10 11 12 13 | // ICMP public boolean isOnline() { Runtime runtime = Runtime.getRuntime(); try { 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(); } return false; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 | // TCP/HTTP/DNS (depending on the port, 53=DNS, 80=HTTP, etc.) public boolean isOnline() { try { int timeoutMs = 1500; Socket sock = new Socket(); SocketAddress sockaddr = new InetSocketAddress("8.8.8.8", 53); sock.connect(sockaddr, timeoutMs); sock.close(); return true; } catch (IOException e) { return false; } } |
这在每个设备上都非常可靠,而且速度非常快。它需要在单独的任务中运行(例如,
它真的够快吗?
是的,非常快;-)
除了在互联网上测试一些东西之外,是否没有可靠的方法来检查互联网?
据我所知,但让我知道,我会编辑我的答案。
如果DNS关闭怎么办?
google dns(如
8.8.8.8 )是世界上最大的公共dns。截至2013年,它每天处理1300亿个请求。让我们假设一下,你的应用程序可能不会成为一天的话题。需要哪些权限?
1<uses-permission android:name="android.permission.INTERNET" />仅仅是互联网接入-惊喜^(顺便问一下,你有没有想过,如果没有这个许可,这里建议的一些方法甚至可以有一个关于互联网接入的远程胶水?)
nbsp;
附加:一次启动1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | class InternetCheck extends AsyncTask<Void,Void,Boolean> { private Consumer mConsumer; public interface Consumer { void accept(Boolean internet); } public InternetCheck(Consumer consumer) { mConsumer = consumer; execute(); } @Override protected Boolean doInBackground(Void... voids) { try { Socket sock = new Socket(); sock.connect(new InetSocketAddress("8.8.8.8", 53), 1500); sock.close(); return true; } catch (IOException e) { return false; } } @Override protected void onPostExecute(Boolean internet) { mConsumer.accept(internet); } } /////////////////////////////////////////////////////////////////////////////////// // Usage new InternetCheck(internet -> { /* do something with boolean response */ }); |
附加:一次发射
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | fun hasInternetConnection(): Single<Boolean> { return Single.fromCallable { try { // Connect to Google DNS to check for connection val timeoutMs = 1500 val socket = Socket() val socketAddress = InetSocketAddress("8.8.8.8", 53) socket.connect(socketAddress, timeoutMs) socket.close() true } catch (e: IOException) { false } } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) } /////////////////////////////////////////////////////////////////////////////////// // Usage hasInternetConnection().subscribe { hasInternet -> /* do something */} |
不需要复杂。最简单和框架化的方法是使用
1 2 3 4 5 6 7 | public boolean isOnline() { ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnectedOrConnecting(); } |
如果您考虑到特定的主机和连接类型(wifi/mobile),也可以使用
您还需要:
1 | <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> |
在你的Android清单中。
要使
1 | <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> |
检查此代码…这对我很有用。)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | 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(); } |
然后,我定义处理程序:
1 2 3 4 5 6 7 8 9 10 11 | Handler h = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what != 1) { // code if not connected } else { // code if connected } } }; |
…并启动测试:
1 | isNetworkAvailable(h,2000); // get the answser within 2000 ms |
看一下康涅狄格管理者课程。可以使用此类获取有关主机上活动连接的信息。http://developer.android.com/reference/android/net/connectivitymanager.html
编辑:可以使用
1 2 | Context.getSystemService(Context.CONNECTIVITY_SERVICE) .getNetworkInfo(ConnectivityManager.TYPE_MOBILE) |
或
1 2 | Context.getSystemService(Context.CONNECTIVITY_SERVICE) .getNetworkInfo(ConnectivityManager.TYPE_WIFI) |
并分析返回的networkinfo对象的detailedstate枚举
编辑编辑:要确定是否可以访问主机,可以使用
1 2 | Context.getSystemService(Context.CONNECTIVITY_SERVICE) .requestRouteToHost(TYPE_WIFI, int hostAddress) |
显然,我使用context.getSystemService(context.connectivityu service)作为代理
1 2 | ConnectivityManager cm = Context.getSystemService(Context.CONNECTIVITY_SERVICE); cm.yourMethodCallHere(); |
在处找到并修改了!!)通过此链接:
在清单文件中至少添加:
1 | <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> |
如果您正在访问,您可能已经拥有Internet权限。然后,一个允许测试连接性的布尔函数是:
1 2 3 4 5 6 7 8 9 10 11 12 | private boolean checkInternetConnection() { ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); // test for connection if (cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isAvailable() && cm.getActiveNetworkInfo().isConnected()) { return true; } else { Log.v(TAG,"Internet Connection Not Present"); return false; } } |
我编写了这段代码,它是最简单的,只是一个布尔值。通过询问
如果有连接,并且可以连接到页面,则会得到状态代码
确保添加正确的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | public boolean isOnline() { ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo(); if (netInfo != null && netInfo.isConnected()) { try { URL url = new URL("http://www.google.com"); HttpURLConnection urlc = (HttpURLConnection) url.openConnection(); urlc.setConnectTimeout(3000); urlc.connect(); if (urlc.getResponseCode() == 200) { return new Boolean(true); } } catch (MalformedURLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return false; } |
它确实对我有用:
要验证网络可用性:
1 2 3 4 5 | private Boolean isNetworkAvailable() { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting();} |
要验证Internet访问:
1 2 3 4 5 6 7 8 9 10 11 12 | public Boolean isOnline() { try { Process p1 = java.lang.Runtime.getRuntime().exec("ping -c 1 www.google.com"); int returnVal = p1.waitFor(); boolean reachable = (returnVal==0); return reachable; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return false; } |
我所看到的最短最干净的方法应该是:
1 2 3 4 5 6 7 | public final static boolean isConnected( Context context ) { final ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService( Context.CONNECTIVITY_SERVICE ); final NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); return networkInfo != null && networkInfo.isConnected(); } |
PS:这不会ping任何主机,它只是检查连接状态,因此如果您的路由器没有Internet连接,并且您的设备已连接到它,则此方法将返回true,尽管您没有Internet。
对于实际测试,我建议执行httphead请求(例如,访问www.google.com)并检查状态,如果它的200 OK一切正常,并且您的设备有互联网连接。
不止一条路
第一,最短但效率低的方法
仅需要网络状态权限
1 | <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> |
然后这个方法,
1 2 3 4 5 6 7 8 9 10 11 | public boolean activeNetwork () { ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); boolean isConnected = activeNetwork != null && activeNetwork.isConnected(); return isConnected; } |
从答案中可以看出,
第二,有效途径
需要网络状态和Internet权限
1 2 | <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.INTERNET" /> |
然后这节课,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | public class CheckInternetAsyncTask extends AsyncTask<Void, Integer, Boolean> { private Context context; public CheckInternetAsyncTask(Context context) { this.context = context; } @Override protected Boolean doInBackground(Void... params) { ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); assert cm != null; NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); boolean isConnected = activeNetwork != null && activeNetwork.isConnected(); if (isConnected) { try { HttpURLConnection urlc = (HttpURLConnection) (new URL("http://clients3.google.com/generate_204") .openConnection()); urlc.setRequestProperty("User-Agent","Android"); urlc.setRequestProperty("Connection","close"); urlc.setConnectTimeout(1500); urlc.connect(); if (urlc.getResponseCode() == 204 && urlc.getContentLength() == 0) return true; } catch (IOException e) { Log.e("TAG","Error checking internet connection", e); return false; } } else { Log.d("TAG","No network available!"); return false; } return null; } @Override protected void onPostExecute(Boolean result) { super.onPostExecute(result); Log.d("TAG","result" + result); if(result){ // do ur code } } } |
呼叫
1 | new CheckInternetAsyncTask(getApplicationContext()).execute(); |
一些解释:
你必须在
AsyncTask 上检查因特网,否则在某些情况下会抛出android.os.NetworkOnMainThreadException 。ConnectivityManager 用于检查网络访问是否真的发送请求(ping)请求发送到
http://clients3.google.com/generate_204 ,这个众所周知的url返回一个HTTP状态为204的空页面,这比http://www.google.com 更快更有效,请阅读。如果你有网站,最好是把你的网站,而不是谷歌,只有当你在应用程序中使用它。超时可以更改范围(20毫秒->2000毫秒),通常使用1500毫秒
以下是我使用的方法:
1 2 3 | public boolean isNetworkAvailable(final Context context) { return ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo() != null; } |
更好的是,检查以确保它已"连接":
1 2 3 4 | public boolean isNetworkAvailable(final Context context) { final ConnectivityManager connectivityManager = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)); return connectivityManager.getActiveNetworkInfo() != null && connectivityManager.getActiveNetworkInfo().isConnected(); } |
以下是如何使用该方法:
1 2 3 4 5 | if (isNetworkAvailable(context)) { // code here } else { // code } |
所需权限:
1 | <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> |
https://stackoverflow.com/a/16124915/950427
移动设备上的一个重要用例,用于确保实际连接的存在。这是一个常见的问题,当一个移动用户进入一个wifi网络与"俘获门户",他们需要在其中登录。我在后台使用这个阻塞函数来确保连接的存在。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | /* * Not Thread safe. Blocking thread. Returns true if it * can connect to URL, false and exception is logged. */ public boolean checkConnectionHttps(String url){ boolean responded = false; HttpGet requestTest = new HttpGet(url); HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, 3000); HttpConnectionParams.setSoTimeout(params, 5000); DefaultHttpClient client = new DefaultHttpClient(params); try { client.execute(requestTest); responded = true; } catch (ClientProtocolException e) { Log.w(MainActivity.TAG,"Unable to connect to" + url +"" + e.toString()); } catch (IOException e) { Log.w(MainActivity.TAG,"Unable to connect to" + url +"" + e.toString()); e.printStackTrace(); } return responded; } |
对我来说,检查活动类中的连接状态不是一个好的实践,因为
1 2 | ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); |
应该在那里调用,或者需要将活动实例(上下文)下推到连接处理程序类,以便能够在那里检查连接状态当没有可用的连接(WiFi、网络)时,我会捕获未知的nhostException异常:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | JSONObject jObj = null; Boolean responded = false; HttpGet requestForTest = new HttpGet("http://myserver.com"); try { new DefaultHttpClient().execute(requestForTest); responded = true; } catch (UnknownHostException e) { jObj = new JSONObject(); try { jObj.put("answer_code", 1); jObj.put("answer_text","No available connection"); } catch (Exception e1) {} return jObj; } catch (IOException e) { e.printStackTrace(); } |
通过这种方式,我可以在同一个类中处理这个案例以及其他案例(我的服务器总是用JSON字符串进行响应)。
这对我很有用。试试看。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); try { URL url = new URL("http://stackoverflow.com/posts/11642475/edit" ); //URL url = new URL("http://www.nofoundwebsite.com/" ); executeReq(url); Toast.makeText(getApplicationContext(),"Webpage is available!", Toast.LENGTH_SHORT).show(); } catch(Exception e) { Toast.makeText(getApplicationContext(),"oops! webpage is not available!", Toast.LENGTH_SHORT).show(); } } private void executeReq(URL urlObject) throws IOException { HttpURLConnection conn = null; conn = (HttpURLConnection) urlObject.openConnection(); conn.setReadTimeout(30000);//milliseconds conn.setConnectTimeout(3500);//milliseconds conn.setRequestMethod("GET"); conn.setDoInput(true); // Start connect conn.connect(); InputStream response =conn.getInputStream(); Log.d("Response:", response.toString()); }} |
您可以迭代所有网络连接,并检查是否至少有一个可用连接:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | public boolean isConnected() { boolean connected = false; ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); if (cm != null) { NetworkInfo[] netInfo = cm.getAllNetworkInfo(); for (NetworkInfo ni : netInfo) { if ((ni.getTypeName().equalsIgnoreCase("WIFI") || ni.getTypeName().equalsIgnoreCase("MOBILE")) && ni.isConnected() && ni.isAvailable()) { connected = true; } } } return connected; } |
最佳方法:
1 2 3 4 5 6 7 8 9 10 11 | public static boolean isOnline() { try { InetAddress.getByName("google.com").isReachable(3); return true; } catch (UnknownHostException e){ return false; } catch (IOException e){ return false; } } |
以下是我的
1 2 3 4 5 6 | public static boolean isNetworkAvailable(Context context) { ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); } |
我已经应用了@levit提供的解决方案,并创建了不会调用额外HTTP请求的函数。
它将解决错误
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | public static boolean isInternetAvailable(Context context) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); if (activeNetwork == null) return false; switch (activeNetwork.getType()) { case ConnectivityManager.TYPE_WIFI: if ((activeNetwork.getState() == NetworkInfo.State.CONNECTED || activeNetwork.getState() == NetworkInfo.State.CONNECTING) && isInternet()) return true; break; case ConnectivityManager.TYPE_MOBILE: if ((activeNetwork.getState() == NetworkInfo.State.CONNECTED || activeNetwork.getState() == NetworkInfo.State.CONNECTING) && isInternet()) return true; break; default: return false; } return false; } private static boolean isInternet() { Runtime runtime = Runtime.getRuntime(); try { Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8"); int exitValue = ipProcess.waitFor(); Debug.i(exitValue +""); return (exitValue == 0); } catch (IOException | InterruptedException e) { e.printStackTrace(); } return false; } |
现在称之为,
1 2 3 4 5 | if (!isInternetAvailable(getActivity())) { //Show message } else { //Perfoem the api request } |
检查Android网络/互联网连接状态并不复杂。下面的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | import android.content.Context; import android.net.ConnectivityManager; public class DetectConnection { public static boolean checkInternetConnection(Context context) { ConnectivityManager con_manager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); if (con_manager.getActiveNetworkInfo() != null && con_manager.getActiveNetworkInfo().isAvailable() && con_manager.getActiveNetworkInfo().isConnected()) { return true; } else { return false; } } } |
有关详细信息,请访问如何检查Android网络/互联网连接状态
您可以使用此方法检测网络可用性-
1 2 3 4 5 6 7 8 9 10 11 12 | public static boolean isDeviceOnline(Context context) { boolean isConnectionAvail = false; try { ConnectivityManager cm = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo(); return netInfo.isConnected(); } catch (Exception e) { e.printStackTrace(); } return isConnectionAvail; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | public class Network { Context context; public Network(Context context){ this.context = context; } public boolean isOnline() { ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); return activeNetwork != null && activeNetwork.isConnectedOrConnecting(); } } |
我使用此代码而不是inetAddress:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | try { URL url = new URL("http://"+params[0]); HttpURLConnection urlc = (HttpURLConnection) url.openConnection(); urlc.setRequestProperty("User-Agent","Android Application:"+Z.APP_VERSION); urlc.setRequestProperty("Connection","close"); urlc.setConnectTimeout(1000 * 30); // mTimeout is in seconds urlc.connect(); if (urlc.getResponseCode() == 200) { Main.Log("getResponseCode == 200"); return new Boolean(true); } } catch (MalformedURLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } |
使用ConnectivityManager的其他答案是错误的,因为网络连接并不意味着您可以访问Internet。例如,用户可能连接到咖啡店的WiFi门户,但无法连接到互联网。要检查Internet是否可以访问,您必须尝试连接到实际的服务器。通常,当您想这样做的时候,您会想到一个您想要连接的特定服务器,所以继续检查您是否可以连接到该服务器。下面是检查服务器连接的简单方法。
1 2 3 4 5 6 7 8 9 10 | private boolean isOnTheInternet() { try { URLConnection urlConnection = new URL("http://yourserver").openConnection(); urlConnection.setConnectTimeout(400); urlConnection.connect(); return true; } catch (Exception e) { return false; } } |
设置connectTimeout的原因是,否则它将默认为TCP超时,该超时可以长达几秒。
还要注意,Android不会让你在主线程上运行这个。
检查是否与isavailable()连接以及是否可以与isconnected()建立连接非常重要
1 2 3 4 5 6 7 | private static ConnectivityManager manager; public static boolean isOnline(Context context) { ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); return networkInfo != null && networkInfo.isAvailable() && networkInfo.isConnected(); } |
您还可以取消网络活动WiFi的类型:
1 2 3 4 5 | public static boolean isConnectedWifi(Context context) { ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); return networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_WIFI; } |
或移动M_vil:
1 2 3 4 5 | public static boolean isConnectedMobile(Context context) { ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); return networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_MOBILE; } |
不要忘记权限:
1 2 | <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.INTERNET" /> |
这在Android文档中有介绍http://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html
此方法为您提供了一个快速方法(用于实时反馈)或较慢方法(用于需要可靠性的一次性检查)的选项。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | public boolean isNetworkAvailable(bool SlowButMoreReliable) { bool Result = false; try { if(SlowButMoreReliable){ ConnectivityManager MyConnectivityManager = null; MyConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo MyNetworkInfo = null; MyNetworkInfo = MyConnectivityManager.getActiveNetworkInfo(); Result = MyNetworkInfo != null && MyNetworkInfo.isConnected(); } else { Runtime runtime = Runtime.getRuntime(); Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8"); int i = ipProcess.waitFor(); Result = i== 0; } } catch(Exception ex) { //Common.Exception(ex); //This method is one you should have that displays exceptions in your log } return Result; } |
我把所有的答案都查了一遍,然后我找到了自己的答案,首先检查因特网是否可用,如果因特网可用,然后检查它是否活动。
我已经包含了所有必要的方法和类来检查活跃的互联网连接。
networkutils.class类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | public class NetworkUtils { public static final int STATUS_CONNECTED = 0 ; public static boolean isInternetAvailable(Context ctx){ ConnectivityManager cm = (ConnectivityManager)ctx.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); return activeNetwork != null && activeNetwork.isConnectedOrConnecting(); } public static int isInternetActiveWithPing() { try { Runtime runtime = Runtime.getRuntime(); Process process = runtime.exec("/system/bin/ping -c 1 8.8.8.8"); int exitValue = process.waitFor(); return exitValue; } catch (Exception ex) { return -1; } } public static boolean isInternetActiveWithInetAddress() { try { InetAddress inetAddress = InetAddress.getByName("www.google.com"); return inetAddress != null && !inetAddress.toString().equals(""); } catch (Exception ex) { return false; } } public static void displayInternetConnectionMessage(Context ctx){ Toast.makeText(ctx,"Check Internet Connection", Toast.LENGTH_SHORT).show(); } } |
您可以使用以下代码检查Internet是否处于活动状态:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | private void checkInternetConnection() { if (NetworkUtils.isInternetAvailable(this)) { new Thread(new Runnable() { @Override public void run() { if (NetworkUtils.isInternetActiveWithPing() == NetworkUtils.STATUS_CONNECTED) { performNetworkingOperations(); } else { if (NetworkUtils.isInternetActiveWithInetAddress()) { performNetworkingOperations(); } else { displayConnectionMessage(); } } } }).start(); } else { displayConnectionMessage(); } } private void performNetworkingOperations() { runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(MainActivity.this,"Internet is Available", Toast.LENGTH_SHORT).show(); } }); } private void displayConnectionMessage() { runOnUiThread(new Runnable() { @Override public void run() { NetworkUtils.displayInternetConnectionMessage(MainActivity.this); } }); } |
更新日期:2015年6月29日如果您使用的是xamarin.android,并且想要检查连接,您可以使用一个nuget包,在多个平台上提供此功能。好的候选人到处都是。[更新结束]
上面的答案很好,但是它们都是Java,几乎所有的都检查连接。在我的例子中,我需要与特定类型的连接进行连接,并且我正在xamarin.android上开发。此外,我不会在硬件层中传递对活动上下文的引用,而是使用应用程序上下文。所以这是我的解决方案,以防有人来这里有类似的要求。但是我还没有完成完整的测试,一旦我完成测试,就会更新答案。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | using Android.App; using Android.Content; using Android.Net; namespace Leopard.Mobile.Hal.Android { public class AndroidNetworkHelper { public static AndroidNetworkStatus GetWifiConnectivityStatus() { return GetConnectivityStatus(ConnectivityType.Wifi); } public static AndroidNetworkStatus GetMobileConnectivityStatus() { return GetConnectivityStatus(ConnectivityType.Mobile); } #region Implementation private static AndroidNetworkStatus GetConnectivityStatus(ConnectivityType connectivityType) { var connectivityManager = (ConnectivityManager)Application.Context.GetSystemService(Context.ConnectivityService); var wifiNetworkInfo = connectivityManager.GetNetworkInfo(connectivityType); var result = GetNetworkStatus(wifiNetworkInfo); return result; } private static AndroidNetworkStatus GetNetworkStatus(NetworkInfo wifiNetworkInfo) { var result = AndroidNetworkStatus.Unknown; if (wifiNetworkInfo != null) { if (wifiNetworkInfo.IsAvailable && wifiNetworkInfo.IsConnected) { result = AndroidNetworkStatus.Connected; } else { result = AndroidNetworkStatus.Disconnected; } } return result; } #endregion } public enum AndroidNetworkStatus { Connected, Disconnected, Unknown } |
只需创建以下检查Internet连接的类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | public class ConnectionStatus { private Context _context; public ConnectionStatus(Context context) { this._context = context; } public boolean isConnectionAvailable() { ConnectivityManager connectivity = (ConnectivityManager) _context .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) { return true; } } return false; } } |
此类只包含返回连接状态的布尔值的方法。因此,简单来说,如果方法找到了有效的互联网连接,返回值为
然后,mainActivity中的以下方法从前面描述的方法调用结果,并提示用户相应地执行操作:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | public void addListenerOnWifiButton() { Button btnWifi = (Button)findViewById(R.id.btnWifi); iia = new ConnectionStatus(getApplicationContext()); isConnected = iia.isConnectionAvailable(); if (!isConnected) { btnWifi.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS)); Toast.makeText(getBaseContext(),"Please connect to a hotspot", Toast.LENGTH_SHORT).show(); } }); } else { btnWifi.setVisibility(4); warning.setText("This app may use your mobile data to update events and get their details."); } } |
在上述代码中,如果结果为假(因此没有互联网连接,用户将被带到Android Wi-Fi面板,在该面板中,系统会提示用户连接到Wi-Fi热点。
1 2 3 4 5 6 7 8 9 | public static boolean isNetworkAvailable(Context ctx) { ConnectivityManager connMgr = (ConnectivityManager)ctx.getSystemService(Context.CONNECTIVITY_SERVICE); if(connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected() || connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnected()){ return true; } return false; } |
用户此
1 2 3 4 5 6 7 8 | public boolean isOnline() { boolean var = false; ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); if ( cm.getActiveNetworkInfo() != null ) { var = true; } return var; } |
我是这样做的。我想是稍微短一点,可读性更强。
干杯!
赛亚人
有更多的方法来编码真是太好了。这是我的例子。
1 2 3 4 5 6 7 8 9 10 | ConnectivityManager icheck = getSystemService(Context.CONNECTIVITY_SERVICE); TextView tv = findViewById(R.id.textView1); boolean wifi = icheck.getActiveNetworkInfo() != null; if(wifi) { tv.setText("Internet is on."); } else { tv.setText("Internet is off."); } |
祝你好运。
如果您使用的是API 23或更高版本,您现在可以使用由Google自己的Ping服务支持的NetworkCapabilities.net功能验证来检查Internet是否处于活动状态。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | ConnectivityManager.NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback() { @Override public void onLost(Network network) { // handle network lost } @Override public void onAvailable(Network network) { ConnectivityManager cm = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = cm.getNetworkInfo(network); boolean isConnected = (info != null && info.isConnectedOrConnecting()); if (isConnected) { NetworkCapabilities nc = cm.getNetworkCapabilities(network); if (nc != null) { boolean isInternetValid = nc.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED); if (isInternetValid) { // internet is valid } } } } }; NetworkRequest request = new NetworkRequest.Builder().addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).build(); ConnectivityManager connectivityManager = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE); connectivityManager.registerNetworkCallback(request, networkCallback); |
我尝试了5种以上不同的Android方法,发现这是谷歌提供的最佳解决方案,尤其是Android:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | try { HttpURLConnection urlConnection = (HttpURLConnection) (new URL("http://clients3.google.com/generate_204") .openConnection()); urlConnection.setRequestProperty("User-Agent","Android"); urlConnection.setRequestProperty("Connection","close"); urlConnection.setConnectTimeout(1500); urlConnection.connect(); if (urlConnection.getResponseCode() == 204 && urlConnection.getContentLength() == 0) { Log.d("Network Checker","Successfully connected to internet"); return true; } } catch (IOException e) { Log.e("Network Checker","Error checking internet connection", e); } |
它是
最简单的解决方案是
在大多数情况下,只有当一个人想要连接到远程服务器时,他/她才会检查Internet连接,因此简单而最佳的解决方案是按如下方式Ping您的服务器。
1 2 3 4 5 6 7 8 9 10 11 12 | public boolean isConnected() { final String command ="ping -c 1 yourExmapleDomain.com"; boolean isConnected = false; try { isConnected = Runtime.getRuntime().exec(command).waitFor() == 0; } catch (InterruptedException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return isConnected; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | public static boolean isNetworkAvailable(Context context) { boolean flag = checkNetworkAvailable(context); if (!flag) { Log.d("","No network available!"); } return flag; } private static boolean checkNetworkAvailable(Context context) { ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); return activeNetworkInfo != null; } |
此代码将帮助您找到Internet是否打开。
1 2 3 4 5 6 | public final boolean isInternetOn() { ConnectivityManager conMgr = (ConnectivityManager) this.con .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = conMgr.getActiveNetworkInfo(); return (info != null && info.isConnected()); } |
此外,还应提供以下权限
1 2 | <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> |
如果需要检查Internet连接,请使用此方法对服务器执行ping操作:
1 2 3 4 5 6 7 8 9 | public boolean checkIntCON() { try { Process ipProcess = Runtime.getRuntime().exec("/system/bin/ping -c 1 8.8.8.8"); return (ipProcess.waitFor() == 0); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } return false; } |
您可以使用检查通过使用端口
1 2 3 4 5 6 7 8 9 10 11 12 | public boolean checkIntCON() { try { Socket sock = new Socket(); SocketAddress sockaddr = new InetSocketAddress("8.8.8.8", 80); // port will change according to protocols sock.connect(sockaddr, 1250); sock.close(); return true; } catch (IOException e) { return false; } } |
这是检查Internet连接的最佳方法。这种方法所做的是执行一系列检查,"手机是否处于飞行模式,手机是否连接到网络等"。如果所有检查都返回true,那么该方法将从Internet下载一个文件,并查看内容是否与预期值匹配。
与对服务器执行ping以检查Internet连接的其他方法相比,此方法的好处是:
Android运行时在不同的手机上有所不同,因此您可能无法始终执行这些命令,如图所示:为什么ping在某些设备上工作而不是在其他设备上工作?
由于wifi网络上的登录页面/重定向可能会给人一种错误的连接印象,因此对服务器执行ping操作并不总是有效。
这个答案是用kotlin编写的,并使用fuel库从Internet上下载一个文件,方法是cx1〔0〕,但是只要确保没有缓存HTTP请求,任何库都可以被替换。把
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | private val networkReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { val activeNetworkInfo = (context?.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager).activeNetworkInfo if (activeNetworkInfo != null) { if (activeNetworkInfo.isConnectedOrConnecting) { //Launches a coroutine to fetch file asynchronously launch { try { //Downloads file from url on the internet - use any library you want here. val connectionStatus = fetchUrlAsString(<url_for_file_on_internet>) //check if the contents of the file is as expected if (connectionStatus =="Connected To Database") { hideConnectionWarning() } else { showConnectionWarning() } } catch (e: Exception) { //Catches an exception - fetchUrlAsString only throws an exception if there is no internet showConnectionWarning() } } } else { showConnectionWarning() } } else { showConnectionWarning() } } } private suspend fun fetchUrlAsString(url: String): String = suspendCoroutine { cont -> url.httpGet().header(Pair("pragma","no-cache"), Pair("cache-control","no-cache")).responseString { _, _, result -> when (result) { is Result.Failure -> { cont.resumeWithException(result.getException()) } is Result.Success -> { cont.resume(result.value) } } } } |
您将需要以下权限:
1 2 | <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.INTERNET" /> |
这是检查WiFi和移动数据的互联网连接最简单和容易的方法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | public static boolean isConnected(Activity _context) { if (_context != null) { ConnectivityManager connMgr = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeInfo = connMgr.getActiveNetworkInfo(); if (activeInfo != null && activeInfo.isConnected()) { boolean wifiConnected = activeInfo.getType() == ConnectivityManager.TYPE_WIFI; boolean mobileConnected = activeInfo.getType() == ConnectivityManager.TYPE_MOBILE; if (wifiConnected || mobileConnected) { Log.d(TAG,"Wifi Connected"); return true; } else { showAlert(_context,_context.getString(R.string.err_no_internet)); return false; } } else { showAlert(_context,_context.getString(R.string.err_no_internet)); return false; } } else { Log.e(TAG,"networkConnectivity: Context NULL"); } return false; } |
Android提供ConnectivityManager类来了解Internet连接状态。以下方法对于了解Internet连接状态非常有用。
首先向androidmanifest.xml添加internet和access_network_state权限
1 2 | <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> |
然后使用以下方法检查设备是否连接到Internet。如果设备连接到Internet,此方法将返回true。
1 2 3 4 5 6 7 | public boolean isInternetAvailable(Context context) { ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo(); return activeNetwork != null && activeNetwork.isConnectedOrConnecting(); } |
参考链接:http://www.androidtutorialshub.com/android-check-internet-connection-status/
下面是一些现代代码,它使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | class TestInternet extends AsyncTask<Void, Void, Boolean> { @Override protected Boolean doInBackground(Void... params) { try { URL url = new URL("http://www.google.com"); HttpURLConnection urlc = (HttpURLConnection) url.openConnection(); urlc.setConnectTimeout(3000); urlc.connect(); if (urlc.getResponseCode() == 200) { return true; } } catch (MalformedURLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); return false; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } return false; } @Override protected void onPostExecute(Boolean result) { if (!result) { // code if not connected AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setMessage("An internet connection is required."); builder.setCancelable(false); builder.setPositiveButton( "TRY AGAIN", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); new TestInternet().execute(); } }); AlertDialog alert11 = builder.create(); alert11.show(); } else { // code if connected doMyStuff(); } } } |
…
1 | new TestInternet().execute(); |
您也可以使用以下代码检查Internet:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 | public class CheckInternetConnection { public Context context = null; public CheckInternetConnection(Context ctx) { this.context = ctx; } public boolean CheckInternet() { return isOnline(); } public Boolean isOnline() { try { if(isNetAvailable(context)) return true; else { 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(3000); // This is time limit if the // connection time limit try { urlc.connect(); Log.e("TAG"," urlc ----------" + urlc.getResponseCode()); if (urlc.getResponseCode() == 200) { return true; } }catch (Exception e){ e.printStackTrace(); } } catch (MalformedURLException e1) { e1.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }catch (Exception e){ e.printStackTrace(); } return false; } public synchronized static boolean isNetAvailable(Context context){ try{ boolean isNetAvailable=false; if ( context != null ) { ConnectivityManager mgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); if ( mgr != null ) { boolean mobileNetwork = false; boolean wifiNetwork = false; boolean wiMaxNetwork = false; boolean mobileNetworkConnecetd = false; boolean wifiNetworkConnecetd = false; boolean wiMaxNetworkConnected = false; NetworkInfo mobileInfo = mgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); NetworkInfo wifiInfo = mgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI); NetworkInfo wiMaxInfo = mgr.getNetworkInfo(ConnectivityManager.TYPE_WIMAX); if ( mobileInfo != null ) mobileNetwork = mobileInfo.isAvailable(); if ( wifiInfo != null ) wifiNetwork = wifiInfo.isAvailable(); if(wiMaxInfo != null) wiMaxNetwork = wiMaxInfo.isAvailable(); if(wifiNetwork == true) wifiNetworkConnecetd = wifiInfo.isConnectedOrConnecting(); if(mobileNetwork == true) mobileNetworkConnecetd = mobileInfo.isConnectedOrConnecting(); if(wiMaxNetwork == true) wiMaxNetworkConnected = wiMaxInfo.isConnectedOrConnecting(); isNetAvailable = ( mobileNetworkConnecetd || wifiNetworkConnecetd || wiMaxNetworkConnected ); } } return isNetAvailable; }catch(NullPointerException e) { return false; }catch(Exception e) { return false; } } } |
1 2 3 4 5 6 | public boolean isNetworkAvailable(Context context) { ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); } |
以下是您需要的权限:
1 | <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> |
此线程中的大多数答案仅检查是否有可用的连接,但不检查该连接是否工作,其他答案不在设备范围内,我的解决方案应在每个设备上工作。
在启动应用程序之前,您可以在主活动中删除我的代码,它将快速确定是否存在实际的Internet连接,如果存在,则会立即删除对话框并启动应用程序,如果没有,则会弹出一条警告,说明应用程序需要Internet连接才能工作。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | final AlertDialog alertDialog = new AlertDialog.Builder(this).create(); alertDialog.setTitle("Checking Connection"); alertDialog.setMessage("Checking..."); alertDialog.show(); new CountDownTimer(5000, 1000) { @Override public void onTick(long millisUntilFinished) { new Thread(new Runnable() { public void run() { try { URL url = new URL("http://web.mit.edu/"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(5000); isConnected = connection.getResponseCode() == HttpURLConnection.HTTP_OK; } catch (Exception e) { e.printStackTrace(); } } }).start(); if (isConnected == false){ alertDialog.setMessage("Try" + (5 - millisUntilFinished/1000) +" of 5."); } else { alertDialog.dismiss(); } } @Override public void onFinish() { if (isConnected == false) { alertDialog.dismiss(); new AlertDialog.Builder(activity) .setTitle("No Internet") .setMessage("Please connect to Internet first.") .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // kill the app? } }) .setIcon(android.R.drawable.ic_dialog_alert) .show(); } else { // Launch the app } } }.start(); |
不要忘记将此权限添加到清单:
1 2 | <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | if(isConnected()){ Toast.makeText(getApplication(),"Thank you",Toast.LENGTH_SHORT).show(); } else{ AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.AppCompatAlertDialogStyle); builder.setTitle("Amar Bhat"); builder.setMessage("Oops...You are not connected to Internet!!!"); builder.setPositiveButton("OK", null); builder.setNegativeButton("Cancel", null); builder.show(); //Toast.makeText(getApplication(),"You are not connected",Toast.LENGTH_SHORT).show(); } //And outside the class define isConnected() public boolean isConnected(){ ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isConnected()) return true; else return false; } // In minifest add these permission <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> |
不要检查WiFi连接或移动数据连接,尝试访问任何托管域。这样,您就可以检查WiFi/移动连接是否能够连接公共互联网。
如果您的移动设备能够连接到提供的公共域,则返回以下内容。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | boolean isReachable() { boolean connected = false; String instanceURL ="Your trusted domain name"; Socket socket; try { socket = new Socket(); SocketAddress socketAddress = new InetSocketAddress(instanceURL, 80); socket.connect(socketAddress, 5000); if (socket.isConnected()) { connected = true; socket.close(); } } catch (IOException e) { e.printStackTrace(); } finally { socket = null; } return connected; } |
希望能有所帮助。
科特林:
1 2 3 4 5 6 7 8 | class UtilityMethods { companion object { fun isConnected(activity: Activity): Boolean { val connectivityManager: ConnectivityManager = activity.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager return null != connectivityManager.activeNetworkInfo } }} |
在活动类内调用isconnected为:
1 | UtilityMethods.isConnected(this) |
片段类内部为:
1 | UtilityMethods.isConnected(activity) |