Subtracted that you can check the Internet connection with
android.permission.ACCESS_NETWORK_STATE Or
android.net.ConnectivityManager But all this is only using java. Is it possible to do this with Shell?
Subtracted that you can check the Internet connection with
android.permission.ACCESS_NETWORK_STATE Or
android.net.ConnectivityManager But all this is only using java. Is it possible to do this with Shell?
Can check this way
public boolean isOnline() { ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo(); return netInfo != null && netInfo.isConnectedOrConnecting(); } But, in this method of checking there is one big minus. Only the connection to the network is checked (wifi, 3g, 4g, etc.) If you are connected to WIFI and there is no Internet, the service will show that there is a connection. Although, in fact it is not.
As for PING , not all manufacturers add the executable file . I often met Chinese devices where there is no PING file.
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; } As practice shows, it is best to make a request to some site, such as Google.com and track the response to the subject UnknownHostException
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; } } And do not forget that all network operations need to be done in a separate thread
And you need to add 2 permishena in Manifests
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> It may seem like a crutch, but I believe that this is the most reliable way: send a request to a website that can return some data (for example, in JSON format) and if the answer comes from the server, then the Internet is there, if an error occurs, then it is not. It is very easy to implement if you will use the library Retrofit 2
Source: https://ru.stackoverflow.com/questions/640602/
All Articles